pandas 数据框中的内部联接/合并比左侧数据框中的行多 [英] inner join/merge in pandas dataframe give more rows than left dataframe

查看:62
本文介绍了 pandas 数据框中的内部联接/合并比左侧数据框中的行多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是数据框列的外观.

Here are how the dataframes columns look like.

df1 ='设备号','日期',....< <其他10列>> 3500条记录

df1='device number', 'date', ....<<10 other columns>> 3500 records

df2 ='设备号','日期',....<< <9其他列>> 14,000条记录

df2='device number', 'date', ....<<9 other columns>> 14,000 records

在每个数据框中,设备号"和日期"都不是唯一的.但是,它们的组合对于标识行是唯一的.

In each data frame, neither 'device number', nor 'date' are unique. However, their combination is unique to identify a row.

我正在尝试形成一个新数据帧,该数据帧与df1和df2中的行(设备编号和日期都相等)匹配,并具有这些df1和df2中的所有列.我正在尝试的pandas命令是

I am trying to form a new data frame which matches the rows from df1 and df2 where both device number and date are equal, and have all the columns from these df1 and df2. The pandas command I am trying is

df3=pd.merge(df1, df2, how='inner', on=['device number', 'date'])

但是,df3给了我一个形状为(14,000,21)的数据框.列号是有意义的,但是内部联接的行数比左边的任何数据帧都多吗?这是否意味着我对内部联接的理解存在缺陷?另外,如何获得我描述的结果?

However, df3 gives me a dataframe of shape (14,000, 21). The column number makes sense, but how can the inner join has more rows than any of the left dataframes? Does it mean I have a flaw in my understanding of inner join? Also, how can I achieve the result I described?

推荐答案

只有这样,我才能看到这种情况……尤其是如果14,000是与df2中的记录数完全相同的数字,则是列组合df2中的不是唯一.

Only way I can see this happening... particularly with the 14,000 being the same exact number as the number of records in df2 is if the column combination in df2 are not unique.

您可以使用以下命令验证它们是否唯一(True如果唯一)

You can verify that they are not unique with the following (True if unique)

df2.duplicated(['device number', 'date']).sum() == 0

df.set_index(['device number', 'date']).index.is_unique

这篇关于 pandas 数据框中的内部联接/合并比左侧数据框中的行多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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