JavaScript
x
4
1
>> masks = [[1,1],[0,0]]
2
>> [np.ma.masked_array(data=np.array([1.0,2.0]), mask=m, fill_value=np.nan).mean() for m in masks]
3
[masked, 1.5]
4
I’d like to replace the masked
result with nan
. Is there a way to do that directly with numpy’s masked_array
?
Advertisement
Answer
JavaScript
1
2
1
In [232]: M = np.ma.masked_array(data=np.array([1.0,2.0]),mask=[True, False])
2
filled
method replaces the masked values with the fill value:
JavaScript
1
5
1
In [233]: M.filled()
2
Out[233]: array([1.e+20, 2.e+00])
3
In [234]: M.filled(np.nan) # or with a value of your choice.
4
Out[234]: array([nan, 2.])
5
Or as you do, specify the fill value when defining the array:
JavaScript
1
10
10
1
In [235]: M = np.ma.masked_array(data=np.array([1.0,2.0]),mask=[True, False],
2
fill_value=np.nan) :
3
In [236]: M
4
Out[236]:
5
masked_array(data=[--, 2.0],
6
mask=[ True, False],
7
fill_value=nan)
8
In [237]: M.filled()
9
Out[237]: array([nan, 2.])
10
The masked mean method skips over the filled values:
JavaScript
1
8
1
In [238]: M.mean()
2
Out[238]: 2.0
3
In [239]: M.filled().mean()
4
Out[239]: nan
5
In [241]: np.nanmean(M.filled()) # so does the `nanmean` function
6
In [242]: M.data.mean() # mean of the underlying data
7
Out[242]: 1.5
8