如何使用屏蔽值旁邊的值的平均值替換numpy數組中的屏蔽值

[英]How to replace masked values from a numpy array with the average of the values immediately next to the masked value


What is the most efficient numpy way to replace masked values in an array with the average of the closest unmasked values next to them?

使用它們旁邊最接近的未屏蔽值的平均值來替換數組中屏蔽值的最有效的numpy方法是什么?

eg:

a = np.array([2,6,4,8])
b = np.ma.masked_where(a>5,a)
print b

masked_array(data = [2 -- 4 --],
         mask = [False  True False  True],
   fill_value = 999999)

I want the masked values in b to be replaced with the average of values just next to them. Boundaries can repeat the closest unmasked value. So in this example, b will be the following:

我希望b中的掩碼值替換為它們旁邊的值的平均值。邊界可以重復最接近的未屏蔽值。所以在這個例子中,b將是以下內容:

b = [2,3,4,4]

The main reason for this question is to see whether this can be done efficiently without the use of an iterator.

這個問題的主要原因是看看這是否可以在不使用迭代器的情況下有效地完成。

1 个解决方案

#1


-1  

you can use np.interp and np.where

你可以使用np.interp和np.where

import numpy as np

a = np.array([2,6,4,8])
mymask = a>5
b = np.ma.masked_where(mymask,a)

print b
# [2 -- 4 --]

c = np.interp(np.where(mymask)[0],np.where(~mymask)[0],b[np.where(~mymask)[0]])
b[np.where(mymask)[0]] = c

print b
# [2 3 4 4]

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/09/08/724d38a3626cc55566c298253fc857dc.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com