python - 计算每行中缺失/NaN 的数量

标签 python pandas dataframe count 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]

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

最佳答案

您可以首先通过 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

关于python - 计算每行中缺失/NaN 的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30059260/

相关文章:

python - 使用 pandas 从 URL 读取包含多个不同数据类型文件的 zip 文件

python - 在Thrift Python服务器上,如何使用TThreadPoolServer配置池中的最大线程数?

python - 移动平均线 Pandas

python - 如何为机器学习有意义地替换 Nan 值

Python数据框按列分组并用百分比创建新列

python - Pandas 创建数据框仅保留另一个数据框的列并附加

r - 如何对 data.frame : R 中的多个升序/降序列进行排序

python - 如何使用Python3.3访问在线MySQL数据库

python - 如何使用 Python 执行方法接口(interface)?

python - 如何在python中找到运行长度编码