Python/Pandas:计算每行中缺失/NaN 的数量 [英] Python/Pandas: counting the number of missing/NaN in each row

查看:38
本文介绍了Python/Pandas:计算每行中缺失/NaN 的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含大量行的数据集.一些值为 NaN,如下所示:

I've got a dataset with a big number of rows. Some of the values are NaN, like this:

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 值的数量,它会是这样的:

And I want to count the number of NaN values in each string, it would be like this:

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

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

What is the best and fastest way to do it?

推荐答案

你可以先通过 isnull() 判断元素是否为 NaN 然后取行-明智的sum(axis=1)

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]

<小时>

或者使用 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/Pandas:计算每行中缺失/NaN 的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆