我们如何使用python pandas并列合并csv?

时间:2018-10-10 09:44:46

标签: python pandas

如果我有三个CSV文件:

file1.csv
file2.csv
file3.csv

每个CSV文件的第一列(A)包含以下值:

file1.csv

A  
asd  
zxc  
qwe

file2.csv

A  
iop  
jkl  
bnm  

file3.csv

A  
rty  
fgh  
vbn

我们如何将这些文件水平合并为具有以下各列的单个文件:

merge.csv

A   B   C   
asd iop rty   
zxc jkl fgh  
qwe bnm vbn 

1 个答案:

答案 0 :(得分:0)

# Read files
data_1 = pd.read_csv(file1.csv)
data_2 = pd.read_csv(file2.csv)   
data_3 = pd.read_csv(file3.csv)   

# Assuming the name A for the first column of each csv is not a typo
data_2.rename(columns={'A': 'B'})
data_3.rename(columns={'A': 'C'})

# Order columns
new_columns = []
for i in range(len(data_1.columns):
    new_columns.extend([data_1.columns[i], data_2.columns[i], data_3.columns[i]])

# Concatenate dataframes
data_out = pd.concat([data_1, data_2, data_3], axis=1)

# Reorder columns
data_out = data_out[new_columns]