pandas 左外联接的结果表大于左表 [英] Pandas Left Outer Join results in table larger than left table

查看:62
本文介绍了 pandas 左外联接的结果表大于左表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我对左外部联接的了解,结果表的行数永远不应超过左表的行数……如果这是错误的话,请告诉我...

From what I understand about a left outer join, the resulting table should never have more rows than the left table...Please let me know if this is wrong...

我的左表是192572行和8列.

My left table is 192572 rows and 8 columns.

我的右边表格是42160行和5列.

My right table is 42160 rows and 5 columns.

我的左"表中有一个名为"id"的字段,该字段与我的右表中的一列键"相匹配.

My Left table has a field called 'id' which matches with a column in my right table called 'key'.

因此,我将它们合并为这样:

Therefore I merge them as such:

combined = pd.merge(a,b,how='left',left_on='id',right_on='key')

但是合并后的形状是236569.

But then the combined shape is 236569.

我误会什么?

推荐答案

如果键与另一个DataFrame中的多个行匹配,则可以预期这种情况会增加:

You can expect this to increase if keys match more than one row in the other DataFrame:

In [11]: df = pd.DataFrame([[1, 3], [2, 4]], columns=['A', 'B'])

In [12]: df2 = pd.DataFrame([[1, 5], [1, 6]], columns=['A', 'C'])

In [13]: df.merge(df2, how='left')  # merges on columns A
Out[13]: 
   A  B   C
0  1  3   5
1  1  3   6
2  2  4 NaN

为避免此行为,请将重复项放在df2中:

In [21]: df2.drop_duplicates(subset=['A'])  # you can use take_last=True
Out[21]: 
   A  C
0  1  5

In [22]: df.merge(df2.drop_duplicates(subset=['A']), how='left')
Out[22]: 
   A  B   C
0  1  3   5
1  2  4 NaN

这篇关于 pandas 左外联接的结果表大于左表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆