python - Python pandas:映射并返回 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
谁能知道为什么要如何解决?
解决方案
问题是列中的值类型不同,因此必须将两者中的相同类型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
推荐阅读
- dask - 如何确定重复(意外)`repartition-split-repartition-merge`任务的原因?
- cookies - 将 JWT 存储在内存中如何不受 XSS 攻击?
- bash - awk 仅在 X 时间后打印结果
- perl - Perl Tk 代码无需用户干预即可将鼠标从一个位置移动到另一个位置
- mks-integrity - MKS:你能有多个延迟签到吗?
- c# - unity c# 获取点击的 ui 文本的值
- selenium - 表格数据不在 HTML
- oracle-apex - Oracle APEX - 修改作为数据库列的项目的会话状态
- python - discord py:使用命令取消循环
- python - 将列中的每个记录名称更改为与 Pandas 中的条件匹配的另一个记录名称