繁体   English   中英

如何在 pandas 中连接两个具有相同值但具有不同列名的表

[英]How to join two tables with the same values but with different column names in pandas

我有两张桌子:

参考编号 参考日期 价格
112 2012-01-01 14.35
205 2012-03-02 10.02
325 2012-04-02 5.40
14 2012-06-20 7.68
票证-reference_id 数量
112 2
205 4
325 7
14 5

我需要加入 reference_id 和 ticket_reference_id 的值,保留列名。

所以,我需要有下一个结果:

参考编号 参考日期 价格 数量
112 2012-01-01 14.35 2
205 2012-03-02 10.02 4
325 2012-04-02 5.40 7
14 2012-06-20 7.68 5

我试图用下一个代码来做,但它没有加入值,它创建列reference_id和ticket-reference_id:

    result = df1.merge(right=df2, how='left', left_on='reference_id', right_on='ticket-reference_id', copy=False)  

让我们尝试在合并之前重命名该列以匹配:

result = df1.merge(df2.rename(columns={'ticket-reference_id': 'reference_id'}),
                   how='left',
                   on='reference_id', 
                   copy=False)
print(result)

result

   reference_id reference_date  price  quantity
0           112     2012-01-01  14.35         2
1           205     2012-03-02  10.02         4
2           325     2012-04-02   5.40         7
3            14     2012-06-20   7.68         5

暂无
暂无

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

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