为什么用字典替换字典列只会创建nan?

问题描述 投票:0回答:1

我想用我的字典替换'GeneID'列。

这仅创建了nan。。有人知道为什么会这样吗?

 df
Out[107]: 
        Region     GeneID  DistanceValue
0           BG   79677107            0.0
       ...        ...            ...
1097355  CERus       1415            NaN
[1097360 rows x 3 columns]

用final_dictionary1代替

df["GeneID"] = df["GeneID"].map(final_dictionary1)

whereas final_dictionary1 looks like:

...
 '52856': 'Mtg2',
 '19886': 'Ros1',
 '16008': 'Igfbp2',
 '14747': 'Cmklr1',
 '13401': 'Dmwd',
 '12545': 'Cdc7',
 '28113': 'Tinf2',
 '71833': 'Dcaf7',
 ...}

是因为数字不是字符串吗?我可以看到df.GeneID中存储了什么吗?如果是数字或字符串。这会导致错误吗?还是为什么不能正确替换呢?

python pandas dictionary
1个回答
0
投票

我认为GeneID中存在数字,因此与字典中的字符串键不匹配,解决方案是将数字转换为字符串:

df["GeneID"] = df["GeneID"].astype(str).map(final_dictionary1)

或:

df["GeneID"] = df["GeneID"].map({int(k):v for k, v in final_dictionary1.items()})
© www.soinside.com 2019 - 2024. All rights reserved.