Saturday, February 12, 2022

Python adding two dataframes having same columns matching values of a particular column

 df1:
        t1  a         b
    0   USD 2,877   -2,418
    1   CNH 600     -593
    2   AUD 756     -106
    3   JPY 113     -173
    4   XAG 8          0

df2:
    t2  a        b
0   CNH 64      -44
1   USD 756     -774
2   JPY 1,127   -2,574
3   TWO 56      -58
4   TWD 38      -231

print (df1.set_index('t1').add(df2.set_index('t2'), fill_value=0)
          .reset_index()
          .rename(columns={'index':'t'}))

     t       a       b
0  AUD   756.0  -106.0
1  CNH   664.0  -637.0
2  JPY  1240.0 -2747.0
3  TWD    38.0  -231.0
4  TWO    56.0   -58.0
5  USD  3633.0 -3192.0
6  XAG     8.0     0.0

references:

 https://stackoverflow.com/questions/39010614/pandas-adding-two-dataframes-on-the-common-columns

No comments:

Post a Comment