2 回答
TA贡献1982条经验 获得超2个赞
问题是列中的值类型不同,code因此有必要将astype两者中的相同类型转换为整数或字符串:
print (df1['code'].dtype)
object
print (df2['code'].dtype)
int64
print (type(df1.loc[0, 'code']))
<class 'str'>
print (type(df2.loc[0, 'code']))
<class 'numpy.int64'>
mapping = dict(df2[['code','name']].values)
#same dtypes - integers
df1['name'] = df1['code'].astype(int).map(mapping)
#same dtypes - object (obviously strings)
df2['code'] = df2['code'].astype(str)
mapping = dict(df2[['code','name']].values)
df1['name'] = df1['code'].map(mapping)
print (df1)
id code name
0 1 2 Ben
1 2 3 John
2 3 3 John
3 4 1 Mary
TA贡献1827条经验 获得超4个赞
另一种方法是使用 dataframe.merge
df.merge(df2.drop(['id'],1), how='left', on=['code'])
输出:
id code name
0 1 2 Ben
1 2 3 John
2 3 3 John
3 4 1 Mery
添加回答
举报