使用map和replace转换DataFrame列时出现NaN及未替换问题
映射/替换失效的解决方案
强制统一数据类型:
有时候numpy整数类型(如numpy.int64)和Python原生整数会存在隐性不匹配,导致字典键值无法匹配。先把emotion列转为Python原生int:text_df['emotion'] = text_df['emotion'].astype(int) text_df['text'] = text_df['emotion'].map(label_to_text)改用
apply调用字典get方法:
如果map依然失效,用apply直接调用字典的get方法,兼容性更强:text_df['text'] = text_df['emotion'].apply(lambda x: label_to_text.get(x))验证标签完整性:
确认emotion列的所有值都存在于字典键中,避免因遗漏值导致NaN:missing = text_df[~text_df['emotion'].isin(label_to_text.keys())]['emotion'].unique() print(f"无映射的标签:{missing}")重置索引(可选):
若DataFrame索引与emotion列存在混淆,先重置索引再尝试映射:text_df = text_df.reset_index(drop=True) text_df['text'] = text_df['emotion'].map(label_to_text)
内容的提问来源于stack exchange,提问作者Chubiblan
相关产品推荐
相关产品推荐

