有没有办法将屏蔽的3D numpy数组转换为以NaN代替掩码的numpy数组?这样,我可以使用np.save轻松地将numpy数组写出。另一种选择是找到一种方法来写出被屏蔽的数组,并为被屏蔽的元素提供一些明确的指示符。我试过了:

a = np.ma.zeros((500, 500))
a.dump('test')


但我需要将文件格式设置为可以读入R的格式。谢谢。

最佳答案

扫描the masked array operations page可以显示np.ma.filled可以满足您的需求。例如,

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))


产量

[[[ nan   1.   2.   3.]
  [  4.  nan   6.   7.]
  [  8.   9.  nan  11.]]

 [[ 12.  13.  14.  nan]
  [ 16.  17.  18.  19.]
  [ nan  21.  22.  23.]]]




或者,您可以使用被屏蔽的数组的filledmethodmarr.filled(np.nan)等效于np.ma.filled(marr, np.nan)

关于python - 将带掩码的.numpy掩码数组保存为具有NaN的.numpy数组,其中mask == True,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28730582/

10-14 19:17
查看更多