Skip to content Skip to sidebar Skip to footer

Pandas Concat/merge And Sum One Column

I have two pandas.DataFrame objects with MultiIndex indices. Some of the index values are shared with the two dataframes, but not all. I would like to merge these two data frames a

Solution 1:

In this particular case, I think you could just add them and use fill_value=0, relying on the default alignment behaviour:

>>> df1.add(df2,fill_value=0)
        a  b   c
A0 C0   07NaN
   C1   16NaN
A1 C0   25NaN
   C1   34NaN
A2 C0   435
   C1   534
A3 C0   633
   C1   732
A4 C0 NaN41
   C1 NaN50

There being only one column in common, only one is summed, but if you wanted to make that explicit you could instead do something like

>>>m = pd.concat([df1, df2],axis=1)>>>m["b"] = m.pop("b").sum(axis=1)>>>m
        a   c  b
A0 C0   0 NaN  7
   C1   1 NaN  6
A1 C0   2 NaN  5
   C1   3 NaN  4
A2 C0   4   5  3
   C1   5   4  3
A3 C0   6   3  3
   C1   7   2  3
A4 C0 NaN   1  4
   C1 NaN   0  5

Post a Comment for "Pandas Concat/merge And Sum One Column"