Python/Panda: 计算每行中缺少/NaN 的数量

我得到了一个包含大量行的数据集,其中一些值是 NaN,如下所示:

In [91]: df
Out[91]:
1    3      1      1      1
1    3      1      1      1
2    3      1      1      1
1    1    NaN    NaN    NaN
1    3      1      1      1
1    1      1      1      1

我想要计算每个字符串中 NaN 值的数量,如下所示:

In [91]: list = <somecode with df>
In [92]: list
Out[91]:
[0,
0,
0,
3,
0,
0]

最好和最快的方法是什么?

94749 次浏览

You could first find if element is NaN or not by isnull() and then take row-wise sum(axis=1)

In [195]: df.isnull().sum(axis=1)
Out[195]:
0    0
1    0
2    0
3    3
4    0
5    0
dtype: int64

And, if you want the output as list, you can

In [196]: df.isnull().sum(axis=1).tolist()
Out[196]: [0, 0, 0, 3, 0, 0]

Or use count like

In [130]: df.shape[1] - df.count(axis=1)
Out[130]:
0    0
1    0
2    0
3    3
4    0
5    0
dtype: int64