pandas - Merge two csv files that have a similar row structure but no common index between them
问题描述
I have two csv files that I want to merge, by adding the column information from one csv to another. However they have no common index between them, but they do have the same amount of rows(they are in order). I have seen many examples of joining csv files based on index and on same numbers, however my csv files have no similar index, but they are in order. I've tried a few different examples with no luck.
mycsvfile1
"a","1","mike"
"b","2","sally"
"c","3","derek"
mycsvfile2
"boy","63","retired"
"girl","55","employed"
"boy","22","student"
Desired outcome for outcsvfile3
"a","1","mike","boy","63","retired"
"b","2","sally","girl","55","employed"
"c","3","derek","boy","22","student"
Code:
import csv
import panada
df2 = pd.read_csv("mycsvfile1.csv",header=None)
df1 = pd.read_csv("mycsvfile2.csv", header=None)
df3 = pd.merge(df1,df2)
Using
df3 = pd.merge([df1,df2])
Adds the data into a new row which doesn't help me. Any assistance is greatly appreciated.
解决方案
如果两个数据帧都有编号索引(即从 0 开始并以 1 递增 - 这是 的默认行为pd.read_csv
),并假设两个数据帧已经按正确的顺序排序以便行匹配,那么应该这样做:
df3 = pd.merge(df1,df2, left_index=True, right_index=True)
推荐阅读
- r - 如何在 R 中使用许多变量有效地运行负二项式回归
- arrays - 如何使局部数组变量有条件地指向开放数组参数?
- vscode-settings - VSCODE prettier 格式配置
- c# - 在 DisplayPromptAsync 中预选内容以允许轻松覆盖
- excel - Excel - 检查产品的相同行
- java - 如何将“For Loop”中的数据保存到压缩的“.txt”文件中
- php - PHP array_merge 与 foreach 循环
- google-apps-script - 检测在 Google Sheet 中的数组公式中创建的损坏的图像函数
- c++ - 使用点云检测表面上的空圆形/矩形
- php - 如何在 PHP 中删除字符串中的 HTML 标签和 HTML 内容?