从 numpy 数组中删除只有 NaN 的行和列

Removing rows and columns with only NaN from numpy array

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

在试验面具时,我遇到了这个错误,但不知道为什么。 它适用于行但不适用于列?

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

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

特别是 mask_column.shape(3,) 即尺寸为 3 的 1 维,而 a.shape(5,3),因此 mask_column 无法广播(检查 numpy broadcasting 详细播报解说)。

因此要过滤nan列需要在全选行后将mask作为second dimension传递,即:

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