Merge and sum two data frames where the columns correspond to python pandas

I may be getting close, this is the wrong way. If I have two data frames a and b:

Dataframe A:

a b c
1 2 4
1 6 5
1 8 7

and Dataframe B:

a b c d
1 2 4 9
1 6 5 7
1 8 7 10

And I want to join them, but it's cool to sum the columns where the column name matches, and keep the column names that don't match. So, the final merged table will look like this:

a   b   c   d
2   4   8   9
2   12  10  7
2   16  14  10

Note. Indexes will always match (e.g., as many records in the same order)

+4
source share
2 answers

You can call addin a larger df passing in another df and call fillna:

In [18]:
df1.add(df).fillna(df1)

Out[18]:
   a   b   c   d
0  2   4   8   9
1  2  12  10   7
2  2  16  14  10

Another way is to use combine_first:

In [20]:
df1.add(df).combine_first(df1)

Out[20]:
   a   b   c   d
0  2   4   8   9
1  2  12  10   7
2  2  16  14  10
+5
source

, NAN .

d = pd.DataFrame(data, columns=['a','b','c'])
d2 = pd.DataFrame(data2, columns=['a','b','c','d'])
d, d2 = d.align(d2, fill_value=0)
sum_df = d + d2

In [23]: d
Out[23]: 
   a  b  c  d
0  1  2  4  0
1  1  6  5  0
2  1  8  7  0

In [24]: d2
Out[24]: 
   a  b  c   d
0  1  2  4   9
1  1  6  5   7
2  1  8  7  10

In [25]:sum_df
Out[25]: 
   a   b   c   d
0  2   4   8   9
1  2  12  10   7
2  2  16  14  10
+1

Source: https://habr.com/ru/post/1625559/


All Articles