如何在python中获取数组中NaN的所有元素的索引?

时间:2017-01-18 20:18:12

标签: python arrays python-3.x indexing

我有一个数组

   [     nan,      nan,      nan,  1633.32,  1661.24,     0.  ],
   [     nan,      nan,      nan,  2885.94,  3264.09,     0.  ],
   [  605.48,      nan,   599.27,   664.47,   670.68,     0.  ],
   [     nan,      nan,      nan,   874.59,   783.86,     0.  ],
   [ 1596.01,      nan,  1469.77,  1731.26,  1514.86,     0.  ]]

有没有办法知道" nan"

元素的索引(行,列)

1 个答案:

答案 0 :(得分:1)

np.isnan模块使用np.argwherenumpy函数组合的解决方案:

import numpy as np

arr = np.array([[     np.NaN,      np.NaN,      np.NaN,  1633.32,  1661.24,     0.  ],
   [     np.NaN,      np.NaN,      np.NaN,  2885.94,  3264.09,     0.  ],
   [  605.48,      np.NaN,   599.27,   664.47,   670.68,     0.  ],
   [     np.NaN,      np.NaN,      np.NaN,   874.59,   783.86,     0.  ],
   [ 1596.01,      np.NaN,  1469.77,  1731.26,  1514.86,     0.  ]])

print(np.argwhere(np.isnan(arr)))

输出:

[[0 0]
 [0 1]
 [0 2]
 [1 0]
 [1 1]
 [1 2]
 [2 1]
 [3 0]
 [3 1]
 [3 2]
 [4 1]]