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
添加回答
舉報