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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With