Reputation: 865
Is there a way to convert a masked 3D numpy array to a numpy array with NaNs in place of the mask? This way I can easily write the numpy array out using np.save
. The alternative is to find a way to write out the masked array with some clear indicator for elements that are masked. I have tried:
a = np.ma.zeros((500, 500))
a.dump('test')
but I need the file to be in a format so it can be read into R. Thanks.
Upvotes: 4
Views: 3165
Reputation: 879701
A scan of the masked array operations page shows np.ma.filled
does what you are looking for. For example,
import numpy as np
arr = np.arange(2*3*4).reshape(2,3,4).astype(float)
mask = arr % 5 == 0
marr = np.ma.array(arr, mask=mask)
print(np.ma.filled(marr, np.nan))
yields
[[[ nan 1. 2. 3.]
[ 4. nan 6. 7.]
[ 8. 9. nan 11.]]
[[ 12. 13. 14. nan]
[ 16. 17. 18. 19.]
[ nan 21. 22. 23.]]]
Alternatively, you could use the masked array's filled
method. marr.filled(np.nan)
is equivalent to np.ma.filled(marr, np.nan)
.
Upvotes: 7
Reputation: 81
You can multiply the mask by the data so that all masked elements will equal zero, eg:
a=np.random.rand(500,500)
b=ma.masked_greater(a, .5)
result=b.data*b.mask
This can then be converted to nan using
result[result==0] = np.nan
Upvotes: 1