Python Pandas:如何总结还包含缺失值的列? [英] Python Pandas: How to sum up columns that also include missing values?

查看:37
本文介绍了Python Pandas:如何总结还包含缺失值的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有几列的 df,其中三个是这样的:

I have a df with several columns by three of them are like this:

num1  num2   num3 
1      NaN    1
NaN     1     1
1       1     1

并且我想创建另一列sum_num"并为所有列添加每行中的值(另一种方法是计算 1 的数量,因为这些值都是 1).

and I would like to create another column "sum_num" and add the values in per row for all the columns (alternative would be to count number of ones cause the values are all ones).

预期结果:

num1  num2   num3 sum_num
1      NaN    1      2
NaN     1     1      2
1       1     1      3

现在我已经尝试了这段代码,但是我在sum_num"列中只有 NaN 的内容.

Now I have tried this code but what I am having in the "sum_num" columns in only NaNs.

df['sum_num'] = df.num1 + df.num2 + df.num3

有谁知道如何忽略缺失值并仍然对这些值求和或计算它们以获得每行所需的结果?

Does anybody know how to ignore missing values and still either sum the ones or count them to get the desired outcome per row?

推荐答案

sum on axis=1

In [202]: df['sum_num'] = df.sum(axis=1)

In [203]: df
Out[203]:
   num1  num2  num3  sum_num
0     1   NaN     1        2
1   NaN     1     1        2
2     1     1     1        3

这篇关于Python Pandas:如何总结还包含缺失值的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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