基于 pandas 中的多个键合并两个DataFrame [英] Merge two DataFrames based on multiple keys in pandas
本文介绍了基于 pandas 中的多个键合并两个DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
pandas(或另一个模块)是否具有任何功能来支持基于多个键的两个表的合并(或联接)?
Does pandas (or another module) have any functions to support merge (or join) two tables based on multiple keys?
例如,我有两个表(DataFrames)a
和b
:
For example, I have two tables (DataFrames) a
and b
:
>>> a
A B value1
1 1 23
1 2 34
2 1 2342
2 2 333
>>> b
A B value2
1 1 0.10
1 2 0.20
2 1 0.13
2 2 0.33
所需的结果是:
A B value1 value2
1 1 23 0.10
1 2 34 0.20
2 1 2342 0.13
2 2 333 0.33
推荐答案
To merge by multiple keys, you just need to pass the keys in a list to pd.merge
:
>>> pd.merge(a, b, on=['A', 'B'])
A B value1 value2
0 1 1 23 0.10
1 1 2 34 0.20
2 2 1 2342 0.13
3 2 2 333 0.33
实际上,pd.merge
的默认设置是使用两个DataFrame的列标签的交集,因此pd.merge(a, b)
在这种情况下同样可以很好地工作.
In fact, the default for pd.merge
is to use the intersection of the two DataFrames' column labels, so pd.merge(a, b)
would work equally well in this case.
这篇关于基于 pandas 中的多个键合并两个DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文