所以我可能根本不知道什么是左连接,因为我被绊倒了......这是我对左连接的定义:
Includes matched records from the left and right tables and unmatched records from the LEFT table in the output table.
这是我的例子:
In[87]: df1 = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'b'], 'data1': range(6)})
In[88]: df2 = DataFrame({'key': ['a', 'b', 'a', 'b', 'd'], 'data2': range(5)})
In[89]: pd.merge(df1, df2, on='key', how='left')
Out[86]:
data1 key data2
0 0 b 1
1 0 b 3
2 1 b 1
3 1 b 3
4 2 a 0
5 2 a 2
6 3 c NaN
7 4 a 0
8 4 a 2
9 5 b 1
10 5 b 3
但是!!!我希望得到这个:
data1 key data2
0 0 b 1
1 1 b 1
2 2 a 0
3 3 c NaN
4 4 a 0
5 5 b 1
我的一般想法来自交易数据(例如,我可能会在其中合并标题和项目详细信息,或合并查找数据的会计凭证)。
我的想法或代码中缺少什么来完成这项工作?
PS - 这来自 Wes McKinney 的 Python for Data Analysis 一书(第 179 页) - 他在其中提到了以下内容:
Many-to-many merges have well-defined though not necessarily intuitive behavior. Many-to-many joins form the Cartesian product of the rows. Since there were 3 'b' rows in the left DataFrame and 2 in the right one, there are 6 'b' rows in the result.
我想我错过了这里的重点?
最佳答案
获得预期输出的一种方法是按 data1
分组并获取每组的第一个值:
g = df.groupby('data1').first().reset_index()
返回:
data1 key data2
0 0 b 1
1 1 b 1
2 2 a 0
3 3 c NaN
4 4 a 0
5 5 b 1
希望对您有所帮助。
关于python - Pandas Left Merge/Join not 导致左连接的预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32694597/