python - 合并数据框并复制相似的 ID 值
问题描述
所以我有两个不同大小的数据框,我试图合并它们,同时复制较短列表中的一个元素以匹配较大数据框的形状。
一个数据框有一列文件名,后跟注释列(0 表示否,1 表示是)。此数据框可能包含重复的用户名值。
另一个数据框有一列文件名和一列文本字符串。
print(df1)
Filename Animal Place Food
0 user1.txt 1 0 0
1 user1.txt 0 0 1
2 user2.txt 0 1 0
3 user2.txt 0 0 1
4 user3.txt 1 0 0
print(df2)
Filename Text
0 user1.txt "These cows make for a great steak"
1 user2.txt "Italy has the best pasta"
2 user3.txt "Sharks are my favorite animal"
我想做的是合并文件名上的 2 个数据框,但如果 df1 具有重复的“文件名”值,请保留该“文件名”的相应文本值。因此,例如,最终的数据框将如下所示:
Filename Animal Place Food
0 user1.txt 1 0 0 "These cows make for a great steak"
1 user1.txt 0 0 1 "These cows make for a great steak"
2 user2.txt 0 1 0 "Italy has the best pasta"
3 user2.txt 0 0 1 "Italy has the best pasta"
4 user3.txt 1 0 0 "Sharks are my favorite animal"
如果有人有任何想法,我将不胜感激。
谢谢!
解决方案
利用:
df3 = pd.merge(A, B, left_on='Filename', right_on='Filename')
现在,df3
是您的目标数据框。
推荐阅读
- python - 使用 torchtext.data.TabularDataset 将存储在 G 盘中的 csv 数据加载到 torchtext 格式时出现“没有这样的文件”,
- pandas - 根据文件名python读取多个csv并连接到多个数据帧
- c++ - 如何在 macOS 中监听电源按钮事件?
- php - 将 Laravel 与微服务一起使用:是否可以在没有数据库的情况下使用 eloquent?
- python - networkX 距离矩阵生成器到 pandas DataFrame
- javascript - 从 API 正确获取的数据;应用程序在使用“计算”处理时为 TypeError 提供“未定义”变量
- amazon-web-services - istio 无法安装在通过 AWS 中的 Kops 构建的 Kubernetes 集群中
- python-3.x - 在python中迭代的有效方法是什么?
- python - 如何安排蜘蛛每 5 分钟运行一次?
- javascript - 使用 jQuery 的带星号的 IP 掩码 - 例如 192.168.1.*