Python 查找一个数据帧中的匹配值并发送到另一个数据帧
我有两个数据帧:Python 查找一个数据帧中的匹配值并发送到另一个数据帧,python,pandas,Python,Pandas,我有两个数据帧: df1 Name Age State Postcode AveAge_State_PC John 40 PA 1000 35 Janet 40 LV 1050 30 Jake 30 PA 1000 35 Jess 20 LV 10
df1
Name Age State Postcode AveAge_State_PC
John 40 PA 1000 35
Janet 40 LV 1050 30
Jake 30 PA 1000 35
Jess 20 LV 1050 30
df2
State Postcode AveAge_State_PC
PA 1000 ???
LV 1050 ???
如何将值放入第二个表中?它们都应该是一样的,所以很乐意接受出现的第一个值
我试过:
df2 = df2.merge(df1[['State', 'Postcode', 'AveAge_State_PC']], how = 'left',
left_on = ['State', 'Postcode'], right_on = ['State', 'Postcode']).drop(columns= ['State', 'Postcode'])
但是得到一个
ValueError:您正在尝试合并int64和对象列
编辑
我在合并时也会得到重复的行,而不仅仅是在df2
我假设是因为
df1
中有多个相同的值?任何帮助都将不胜感激!谢谢 将df1['Postcode']=df1['Postcode'].astype(str)
或df2['Postcode']=df2['Postcode'].astype(int)
转换为相同的类型谢谢!foxed错误问题,但我没有在df2
中获得重复的行(已对POST进行了编辑您是对的,请检查,非常感谢!!