python - Combine two pandas dataframes adding corresponding values -
i have 2 dataframes these:
df1 = pd.dataframe({'a': [1,0,3], 'b':[0,0,1], 'c':[0,2,2]}, index =['a','b','c']) df2 = pd.dataframe({'a': [0,0], 'b':[2,1]}, index =['a','c'])
df1 , df2:
| | b | c | | | b | ---|---|---|---| ---|---|---| | 1 | 0 | 0 | | 0 | 2 | b | 0 | 0 | 2 | c | 0 | 1 | c | 3 | 1 | 2 |
and expected result is:
| | b | c | ---|---|---|---| | 1 | 2 | 0 | b | 0 | 0 | 2 | c | 3 | 2 | 2 |
i'm having problems because there may missing columns/rows in of dataframes (df1 may not have columns , rows df2 has)
going idea in answer question - merge 2 dataframes in pandas: join on columns, sum others
since in case, indexes ones common, can use pandas.concat()
2 dataframes, dataframe.groupby
based on index, , take sum on it. example -
in [27]: df1 out[27]: b c 1 0 0 b 0 0 2 c 3 1 2 in [28]: df2 out[28]: b 0 2 c 0 1 in [29]: pd.concat([df1,df2]).groupby(level=0).sum() out[29]: b c 1 2 0 b 0 0 2 c 3 2 2
Comments
Post a Comment