Python 熊猫:映射并返回 Nan

我有两个数据框,第一个是:


id code

1   2

2   3

3   3

4   1

第二个是:


id code  name

1    1   Mary

2    2   Ben

3    3   John

我想映射数据框 1,使其看起来像:


id code  name

1   2    Ben

2   3    John

3   3    John

4   1    Mary

我尝试使用此代码:


mapping = dict(df2[['code','name']].values)

df1['name'] = df1['code'].map(mapping)

我的映射是正确的,但是映射值都是NAN:


mapping = {1:"Mary", 2:"Ben", 3:"John"}


id code  name

1   2    NaN

2   3    NaN

3   3    NaN

4   1    NaN

谁能知道为什么要解决?


慕容森
浏览 256回答 2
2回答

临摹微笑

问题是列中的值类型不同,code因此有必要将astype两者中的相同类型转换为整数或字符串:print (df1['code'].dtype)objectprint (df2['code'].dtype)int64print (type(df1.loc[0, 'code']))<class 'str'>print (type(df2.loc[0, 'code']))<class 'numpy.int64'>mapping = dict(df2[['code','name']].values)#same dtypes - integersdf1['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)&nbsp; &nbsp;id code&nbsp; name0&nbsp; &nbsp;1&nbsp; &nbsp; 2&nbsp; &nbsp;Ben1&nbsp; &nbsp;2&nbsp; &nbsp; 3&nbsp; John2&nbsp; &nbsp;3&nbsp; &nbsp; 3&nbsp; John3&nbsp; &nbsp;4&nbsp; &nbsp; 1&nbsp; Mary

GCT1015

另一种方法是使用 dataframe.mergedf.merge(df2.drop(['id'],1), how='left', on=['code'])输出:&nbsp; &nbsp; id&nbsp; code&nbsp; &nbsp;name0&nbsp; &nbsp;1&nbsp; &nbsp;2&nbsp; &nbsp; &nbsp; Ben1&nbsp; &nbsp;2&nbsp; &nbsp;3&nbsp; &nbsp; &nbsp; John2&nbsp; &nbsp;3&nbsp; &nbsp;3&nbsp; &nbsp; &nbsp; John3&nbsp; &nbsp;4&nbsp; &nbsp;1&nbsp; &nbsp; &nbsp; Mery
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python