0

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

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

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
4

1 回答 1

1

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

特别mask_column.shape(3,)大小为 3 的 1 维,而a.shapeis (5,3),因此mask_column无法广播(查看numpy 广播以获取详细的广播解释)。

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

print(a[:, ~mask_column])
[[ 1.  0.]
 [ 0.  0.]
 [ 0.  0.]
 [nan nan]
 [ 2.  4.]]
于 2020-03-07T11:28:41.533 回答