pandas - 合并具有重复条目的列上的两个数据框
问题描述
我有两个看起来像的数据框:
col1 col2
1 a
1 b
2 c
和
col1 col3
1 d
1 e
3 f
如何合并它们(在 col1 上)以获得以下内容?
col1 col2 col3
1 a d
1 b e
2 c Nan
3 Nan f
我试过 pd.merge 但它没有给出预期的结果。
解决方案
你可以这样做:
df1['key'] = df1.groupby('col1').cumcount()
df2['key'] = df2.groupby('col1').cumcount()
res = df1.merge(df2, on=['col1', 'key'], how='outer').drop('key', 1)
print(res)
输出
col1 col2 col3
0 1 a d
1 1 b e
2 2 c NaN
3 3 NaN f
的想法groupby('col1').cumcount()
是为重复的元素创建一个唯一的键。
推荐阅读
- javascript - 通过javascript将csv数据上的utf-16转换为utf-8
- nuget-package - 使用本地 dll 的引用和本地 nuget 包打包一个 .net 标准 2.0 nuget 包
- json - 如何告诉 springdoc-openapi-maven-plugin 生成 YAML 而不是 JSON?
- microsoft-edge-extension - 如何在右侧的多功能框中添加文本和图标
- yosys - 为什么函数 Pass::Pass 可以在 yosys 中的 main() 之前运行?
- excel - 删除所有行除外?
- flutter - 颤振,飞镖无法从函数中获得所需的输出
- docker-compose - 在 Docker 中启动 formsflow.ai 是否必须安装 WSL2?
- momentjs - Momentjs比较完整的ISO字符串不起作用
- c - 打印字符而不是数字时(C 程序)