【问题标题】:Removing rows and columns with only NaN from numpy array从numpy数组中删除只有NaN的行和列
【发布时间】:2020-06-19 22:47:48
【问题描述】:

我正在寻找解决这个问题的方法。

在尝试使用口罩时,我遇到了这个错误,不知道为什么。 它适用于行但不适用于列?

import numpy as np

a = np.array(
    [[1, np.nan, 0],
    [0, np.nan, 0],
    [0, np.nan, 0],
    [np.nan, np.nan, np.nan],
    [2, np.nan, 4]])

mask_row = np.all(np.isnan(a), axis=1)
mask_column = np.all(np.isnan(a), axis=0)
print(a[~mask_row])
print(a[~mask_column])

这是我在最后一条打印语句中得到的错误:

IndexError: boolean index did not match indexed array along dimension 0; dimension is 5 but corresponding boolean dimension is 3

【问题讨论】:

    标签: arrays python-3.x numpy nan


    【解决方案1】:

    这是因为mask_columnarray([False, True, False])

    特别是mask_column.shape(3,) 即尺寸为3 的1 维,而a.shape(5,3),因此mask_column 不能被广播(查看numpy broadcasting 以获得详细的广播解释)。

    因此,要过滤 nan 列,您需要在选择所有行后传递这样的掩码作为第二维,即:

    print(a[:, ~mask_column])
    [[ 1.  0.]
     [ 0.  0.]
     [ 0.  0.]
     [nan nan]
     [ 2.  4.]]
    

    【讨论】:

      猜你喜欢
      • 2018-12-21
      • 1970-01-01
      • 2016-08-15
      • 2015-05-21
      • 2019-12-22
      • 2015-06-08
      • 2016-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多