简体   繁体   English

Pandas:在公共列上添加两个数据帧

[英]Pandas: Adding two dataframes on the common columns

I have 2 tables which have the same columns and I want to add the numbers where the key matches, and if it doesn't then just add it as is in the output df.. I tried combine first, merge, concat and join.. They all create 2 seperate columnd for t1 and t2, but its the same key, so should just be together I know this would be something very basic.. pls could someone help? 我有2个表具有相同的列,我想添加键匹配的数字,如果没有,那么只需在输出df中添加它..我尝试组合首先,合并,连接和连接。他们都为t1和t2创建了2个单独的columnd,但是它是相同的键,所以应该只是在一起我知道这将是非常基本的东西..请问有人可以帮忙吗? thanks vm! 谢谢你!

 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

Output:
t   a          b
USD 3,634   -3,192
CNH 664     -637
AUD 756     -106
JPY 1,240   -2,747
XAG 8          0
TWO 56       -58
TWD 38      -231

First set_index in both DataFrames by first columns and then use add with parameter fill_value=0 : 第一set_index在两个DataFrames通过第一列,然后使用add有参数fill_value=0

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

If need convert output to int : 如果需要将输出转换为int

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

     t     a     b
0  AUD   756  -106
1  CNH   664  -637
2  JPY  1240 -2747
3  TWD    38  -231
4  TWO    56   -58
5  USD  3633 -3192
6  XAG     8     0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM