Skip to content Skip to sidebar Skip to footer

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_

Solution 1:

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

Solution 2:

In practice you can create a subset form a dataframe, here df:

sum_num = df[['num1', 'num2', 'num3']]

then add the subset to df:

df['summed'] = sum_num.sum(axis=1)

Post a Comment for "Python Pandas: How To Sum Up Columns That Also Include Missing Values?"