Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas: How to sum up columns that also include missing values?

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

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).

Expected outcome:

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

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?

like image 267
UserYmY Avatar asked Mar 11 '26 00:03

UserYmY


1 Answers

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
like image 149
Zero Avatar answered Mar 12 '26 18:03

Zero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!