python - Pandas 合并具有不同名称的列并避免重复

标签 python pandas merge

<分区>

如何在两列名称不同的列上合并两个 pandas DataFrame 并保留其中一列?

df1 = pd.DataFrame({'UserName': [1,2,3], 'Col1':['a','b','c']})
df2 = pd.DataFrame({'UserID': [1,2,3], 'Col2':['d','e','f']})
pd.merge(df1, df2, left_on='UserName', right_on='UserID')

这提供了一个像这样的DataFrame

enter image description here

但很明显,我正在合并 UserNameUserID,因此它们是相同的。我希望它看起来像这样。有没有干净的方法可以做到这一点?

enter image description here

只有我能想到的方法是在合并前将列重命名为相同的列,或者在合并后删除其中一个列。如果 pandas 自动丢弃其中一个或者我可以做类似的事情,我会很好

pd.merge(df1, df2, left_on='UserName', right_on='UserID', keep_column='left')

最佳答案

如何将 UserID 设置为索引,然后加入第二个数据帧的索引?

pd.merge(df1, df2.set_index('UserID'), left_on='UserName', right_index=True)

#   Col1    UserName    Col2
# 0    a           1       d
# 1    b           2       e
# 2    c           3       f

关于python - Pandas 合并具有不同名称的列并避免重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39985861/

相关文章:

Python3 使用字典替换

python - 使用精确开始周期重新采样数据帧

从合并中返回不匹配的记录

python - 根据单元格值从 Pandas DataFrame 中删除行

python - 字符串分割对单个字符串有效,但对 pandas 中的一系列字符串无效

Python 并排合并逗号分隔的文本文件

git - 已解决 VS Code 中的 git merge 冲突,但仍显示未解决

python - 尝试使用 cProfile 时出现问题

python - 强制 mysqldb dict 游标返回带有表名的所有列名前缀

python - 为什么在 python 中执行追加操作后列表产品会重复元素