python - pandas.merge 与重合的列名

标签 python pandas merge

考虑以下数据框:

import pandas as pd
df1 = pd.DataFrame({'id': list('fghij'), 'A': ['A' + str(i) for i in range(5)]})
    A id
0  A0  f
1  A1  g
2  A2  h
3  A3  i
4  A4  j
df2 = pd.DataFrame({'id': list('fg'), 'B': ['B' + str(i) for i in range(2)]})
    B id
0  B0  f
1  B1  g
df3 = pd.DataFrame({'id': list('ij'), 'B': ['B' + str(i) for i in range(3, 5)]})
    B id
0  B3  i
1  B4  j

我想将它们合并以获得

    A id    B
0  A0  f   B0
1  A1  g   B1
2  A2  h  NaN
3  A3  i   B3
4  A4  j   B4

灵感来自this answer我试过了

final = reduce(lambda l, r: pd.merge(l, r, how='outer', on='id'), [df1, df2, df3])

但不幸的是它产生了

    A id  B_x  B_y
0  A0  f   B0  NaN
1  A1  g   B1  NaN
2  A2  h  NaN  NaN
3  A3  i  NaN   B3
4  A4  j  NaN   B4

此外,我查看了 this question但我无法根据我的问题调整解决方案。另外,我在 docs for pandas.merge 中没有找到任何选项来实现这一点。

在我的现实世界问题中,数据帧列表可能会更长,数据帧的大小可能会更大。

是否有任何“Pythonic”方法可以直接执行此操作而无需“后处理”?如果 df2 和 df3 的 B 列重叠(因此,如果最终数据帧的 B 列中的某个值可能有多个候选者),那么最好有一个引发异常的解决方案。

最佳答案

考虑pd.concat + groupby

pd.concat([df1, df2, df3], axis=0).groupby('id').first().reset_index()

  id   A    B
0  f  A0   B0
1  g  A1   B1
2  h  A2  NaN
3  i  A3   B3
4  j  A4   B4

关于python - pandas.merge 与重合的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49485759/

相关文章:

python - 如何匹配两个数据框并得到以下结果?

r - 在 `lm()` 值的情况下,将来自 `NA` 的拟合值与数据框匹配

在给定谓词为真的元素之后拆分列表的 Pythonic 方法

Python 请求挂起/卡住

Python - 不带引号的数字列表

python - Pandas 数据框选择

python - 对多个 pandas 数据框执行列重命名和切片

merge - 如何只 merge 一些文件?

c# - 如何获取合并单元格的值?

python - 是否可以在 motor 中对集合进行子类化?