python - 如果相同,熊猫加入删除列
问题描述
我有 2 个数据框df1
,df2
我想根据他们的列加入'C'
import pandas
df1 = pandas.DataFrame(data=[[1,0,2,4],[2,3,1,3]],columns=['A','B','C','D'])
df2 = pandas.DataFrame(data=[[2,2,2,4],[3,4,1,3]],columns=['A','F','C','D'])
df1
A B C D
0 1 0 2 4
1 2 3 1 3
df2
A F C D
0 2 2 2 4
1 3 4 1 3
# Merge the dataframes
dataframe_matched = df1.join(
other=df2.set_index('C'),
on='C',
how="inner",
lsuffix="_left",
rsuffix="_right",
sort=True,
)
dataframe_matched
A_left B C D_left A_right F D_right
1 2 3 1 3 3 4 3
0 1 0 2 4 2 2 4
列D_left
和D_right
是相同的。有没有一种简单的方法可以只保留 1 的原始名称?
dataframe_matched
A_left B C D A_right F
1 2 3 1 3 3 4
0 1 0 2 4 2 2
解决方案
你可以做drop_duplicates
df1.merge(df2,on='C').T.drop_duplicates().T
Out[288]:
A_x B C D_x A_y F
0 1 0 2 4 2 2
1 2 3 1 3 3 4
更新
pd.concat([df1.set_index('C'),df2.set_index('C')],1,keys=['right','left']).\
T.reset_index(level=1).\
drop_duplicates().set_index('level_1',append=True).T
Out[337]:
right left
level_1 A B D A F
C
2 1 0 4 2 2
1 2 3 3 3 4
推荐阅读
- node.js - Strapi / Node.js 私人用户上传
- python - 我可以在 WebApp 中使用 pytesseract 吗?
- r - 网格中的 R 错误。使用 survminer :: ggsurvplot 调用新软件包版本
- android - 按钮文本显示在设计中,但在我运行应用程序时不可用
- abap - 在表表达式组件中使用偏移量和长度变量?
- python - 需要外部库时使用 Maturin
- azure - 如何使用自定义角色和权限保护 Azure 函数终结点?
- python - 在 Function App Python 中修改 Excel 文件
- r - 从R中的不同列创建一个计算连续天数的列
- ios - 无法在 TextField 中创建绑定 - '在范围内找不到 $social'