pandas 左外联接的结果表大于左表

编程入门 行业动态 更新时间:2024-10-25 18:27:06
本文介绍了 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 左外联接的结果表大于左表

本文发布于:2023-10-18 03:17:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502914.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:外联   pandas

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!