python - Save.numpy masked array to a .numpy array with NaNs where mask == True

标签 python numpy

有没有办法将蒙版的 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.]]]

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

关于python - Save.numpy masked array to a .numpy array with NaNs where mask == True,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28730582/

相关文章:

python - 描述符可以用于属性来提供一些声明性信息吗?

python - 可变数量嵌套循环的迭代器

Python-获取图像的白色像素

python - python中的矢量化球贝塞尔函数?

python - 在 Python 中迭代包含在 3d 数组中的 2d 数组

python - 我正在尝试用 Python 制作一个英语到西类牙语的变位器。需要帮助

python - 如何从 Bokeh 中的 DataTable 对象中选择文本

python - 用于 Linux 的 VISA SCPI 命令处理器

python - 巴特沃斯滤波器应用于 pandas 数据帧的列

python - pandas:将具有相同值的连续行分组为一组