【问题标题】:How to get the indices list of all NaN value in numpy array?如何获取numpy数组中所有NaN值的索引列表?
【发布时间】:2016-10-11 19:37:23
【问题描述】:

现在说我有一个 numpy 数组,它被定义为,

[[1,2,3,4],
[2,3,NaN,5],
[NaN,5,2,3]]

现在我想要一个包含所有缺失值索引的列表,在这种情况下为[(1,2),(2,0)]

有什么办法可以做到吗?

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

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

    【讨论】:

    • 如何对具有浮点值的数组执行相同操作?
    【解决方案2】:

    您可以使用np.where 来匹配与数组的Nan 值和map 对应的布尔条件,以生成tuples 的列表。

    >>>list(map(tuple, np.where(np.isnan(x))))
    [(1, 2), (2, 0)]
    

    【讨论】:

    • 我想你想要list( zip(* map( list, np.where(np.isnan(x) ) ) ) )
    【解决方案3】:

    由于x!=x 返回与np.isnan(x) 相同的布尔数组(因为np.nan!=np.nan 将返回True),您也可以这样写:

    np.argwhere(x!=x)
    

    但是,我仍然建议编写 np.argwhere(np.isnan(x)),因为它更具可读性。我只是尝试提供另一种方法来编写此答案中的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-03
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      • 2016-07-22
      • 2013-06-26
      相关资源
      最近更新 更多