Python 基于另一个数据帧的值向数据帧添加新列
我有两个Python 基于另一个数据帧的值向数据帧添加新列,python,pandas,Python,Pandas,我有两个csv文件,我正在使用熊猫读取数据 train.csv包含值,带有标题id,情绪 87,Positive 10,Positive 7,Neutral text.csv包含值,带有标题id,text 7,hello, I think the price if high... 87, you can call me tomorow... .... 我想将text.csv中的文本插入train.csv中,结果如下: 87,Positive, you can call me tomorow.
csv
文件,我正在使用熊猫读取数据
train.csv
包含值,带有标题id,情绪
87,Positive
10,Positive
7,Neutral
text.csv
包含值,带有标题id,text
7,hello, I think the price if high...
87, you can call me tomorow...
....
我想将text.csv
中的文本插入train.csv
中,结果如下:
87,Positive, you can call me tomorow...
有人能帮忙照看熊猫吗
import pandas as pd
train= pd.read_csv("train.csv")
text= pd.read_csv("text.csv")
# this does not work
combined= pd.merge(train, text, on=['id'])
注意
一些id可能不在文件中,因此如果id不存在,我需要设置null在两个数据帧上设置索引,然后添加列:
train.set_index('id')。情绪+文本。set_index('id')。文本
一个简单的方法是
pd.merge(训练,测试,在'id',how='outer')
根据pandas的说法,如果您使用
how
作为outer
,它将使用所有键文件已经有了头,我尝试了,但不起作用,而且,可能会发生一些ID不存在总是显示为空,3个头显示,但没有数据?!