python - Pandas Left Merge/Join not 导致左连接的预期结果

标签 python join pandas merge

所以我可能根本不知道什么是左连接,因为我被绊倒了......这是我对左连接的定义:

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/

相关文章:

python - 使用 scipy curve_fit 拟合错误

python - 从有限的 CSV 列集读取并作为行输出到特定的 JSON 模式

php - 我想查询连接的记录(左连接)并将它们放入 PhP 中的数组结构中,如何?

python - 如何对行进行分组并提取平均值

python - Pandas - 阅读 HTML

python - 删除 pandas 列中的部分字符串

python - 如何从 Python 控制 Windows 应用程序

python - 没有在 Debian 上使用 PyBluez 配对的 RFCOMM?

linux - 加入多个文件

performance - 如何在 Spark SQL 中加入大数据帧? (最佳实践、稳定性、性能)