Python/Pandas:统计每行missing/NaN的个数
Python/Pandas: counting the number of missing/NaN in each row
我有一个包含大量行的数据集。有些值是 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]
最好最快的方法是什么?
您可以先通过 isnull()
查找元素是否为 NaN
,然后按行取 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
而且,如果您希望输出为列表,您可以
In [196]: df.isnull().sum(axis=1).tolist()
Out[196]: [0, 0, 0, 3, 0, 0]
或使用count
喜欢
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
我有一个包含大量行的数据集。有些值是 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]
最好最快的方法是什么?
您可以先通过 isnull()
查找元素是否为 NaN
,然后按行取 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
而且,如果您希望输出为列表,您可以
In [196]: df.isnull().sum(axis=1).tolist()
Out[196]: [0, 0, 0, 3, 0, 0]
或使用count
喜欢
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