Python 熊猫将2个csv与类似的列合并,但标题名称不同
我想将2个csv文件与类似的列合并,但标题名称不同 a、 csv:Python 熊猫将2个csv与类似的列合并,但标题名称不同,python,pandas,csv,Python,Pandas,Csv,我想将2个csv文件与类似的列合并,但标题名称不同 a、 csv: id name country 1 Cyrus MY 2 May US b、 csv: user_id gender 1 female 2 male 我需要的是,c.csv: id name country gender 1 Cyrus MY female 2 May US male 但是当我使用下面的代码时得到的结果 import csv import pandas as pd df1 = pd.read_csv(
id name country
1 Cyrus MY
2 May US
b、 csv:
user_id gender
1 female
2 male
我需要的是,c.csv:
id name country gender
1 Cyrus MY female
2 May US male
但是当我使用下面的代码时得到的结果
import csv
import pandas as pd
df1 = pd.read_csv('a.csv')
df2 = pd.read_csv('b.csv')
df3 = pd.merge(df1,df2, left_on=['id'],right_on=['user_id'], how='outer')
df3.to_csv('c.csv',index=False)
我得到的结果是:
id name country user_id gender
1 Cyrus MY 1 female
2 May US 2 male
您可以将
df2
中的user\u id
列重命名为id
。由于名称相同,因此不会重复
df2 = pd.read_csv('b.csv').rename(columns={'user_id': 'id'})
df3 = pd.merge(df1, df2, on='id', how='outer')
否则,您可以在合并后删除user\u id
列
df3 = df3.drop('user_id', axis=1)
您可以使用
merge
df1.merge(df2,left_on='id',right_on='user_id')
Out[35]:
id name country user_id gender
0 1 Cyrus MY 1 female
1 2 May US 2 male
或concat
pd.concat([df1.set_index('id'),df2.set_index('user_id')],1).reset_index()
Out[38]:
index name country gender
0 1 Cyrus MY female
1 2 May US male
我想df3.drop('user\u id',inplace=True,axis=1)可以解决您的问题。