首页 > 解决方案 > 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.

标签: pandascsvmerge

解决方案


如果两个数据帧都有编号索引(即从 0 开始并以 1 递增 - 这是 的默认行为pd.read_csv),并假设两个数据帧已经按正确的顺序排序以便行匹配,那么应该这样做:

df3 = pd.merge(df1,df2, left_index=True, right_index=True)

推荐阅读