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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With