现在假设我有一个numpy数组,它被定义为:
[[1,2,3,4],
[2,3,NaN,5],
[NaN,5,2,3]]
现在我想要一个包含所有缺失值索引的列表,在这种情况下是[(1,2),(2,0)]
。
有没有办法可以做到这一点?
np.isnan与np.argwhere结合使用。
x = np.array([[1,2,3,4],
[2,3,np.nan,5],
[np.nan,5,2,3]])
np.argwhere(np.isnan(x))
输出:
array([[1, 2],
[2, 0]])
np.where
来匹配数组中对应于Nan
值的布尔条件,并映射每个结果以生成一个tuples
列表。>>>list(map(tuple, np.where(np.isnan(x))))
[(1, 2), (2, 0)]
list( zip(* map( list, np.where(np.isnan(x) ) ) ) )
。 - travelingbones由于x!= x
返回与np.isnan(x)
相同的布尔数组(因为np.nan!= np.nan
将返回True
),您还可以编写:
np.argwhere(x!=x)
但是,我仍然建议编写np.argwhere(np.isnan(x))
,因为它更易读。我只是尝试在此答案中提供另一种编写代码的方式。
x = np.ones((2,2))
x[(0,0)] = np.nan
x = np.ma.masked_invalid(x)
np.sum(x)
argwhere
真是太棒了!不过我有一个附加问题。由于它返回索引列表,是否有任何方法在 numpy 中将这些索引合并成最小的切片列表。例如,我得到[[1,1],[1,2],[1,3],[3,8],[4,8],[5,8]]
,希望得到[[1,1:4],[3:6,8]]
,主要是因为我的数据没有很好的窗口,而且索引列表非常大。 - Bernd Wechner