gpt4 book ai didi

python Pandas : map and return Nan

转载 作者:行者123 更新时间:2023-11-28 20:57:16 28 4
gpt4 key购买 nike

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

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

谁能知道为什么以及如何解决?

最佳答案

问题是 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

关于 python Pandas : map and return Nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53424798/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com