Pandas sum two columns, skipping NaN

with fillna()

frame['c'] = frame.fillna(0)['a'] + frame.fillna(0)['b']

or as suggested :

frame['c'] = frame.a.fillna(0) + frame.b.fillna(0)

giving :

    a   b  c
0   1   3  4
1   2 NaN  2
2 NaN   4  4

Another approach:

>>> frame["c"] = frame[["a", "b"]].sum(axis=1)
>>> frame
    a   b  c
0   1   3  4
1   2 NaN  2
2 NaN   4  4

As an expansion to the answer above, doing frame[["a", "b"]].sum(axis=1) will fill sum of all NaNs as 0

>>> frame["c"] = frame[["a", "b"]].sum(axis=1)
>>> frame
    a   b  c
0   1   3  4
1   2 NaN  2
2 NaN   4  4
3 NaN NaN  0

If you want the sum of all NaNs to be NaN, you can add the min_count flag as referenced in the docs

>>> frame["c"] = frame[["a", "b"]].sum(axis=1, min_count=1)
>>> frame
    a   b  c
0   1   3  4
1   2 NaN  2
2 NaN   4  4
3 NaN NaN  NaN

Tags:

Python

Pandas