You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用嵌套字典替换Pandas DataFrame多列的对应值?

使用嵌套字典批量替换Pandas DataFrame多列值

核心解决方案

直接利用Pandas的DataFrame.replace()方法,该方法原生支持传入以列名为键、对应映射字典为值的嵌套结构,自动匹配列名并完成批量替换:

# 调用replace方法,传入嵌套字典完成替换
df.replace(nested_dict, inplace=True)

# 若需要将替换后的数值转为字符串(匹配你给出的期望输出格式)
target_cols = [col for col in nested_dict.keys()]
df[target_cols] = df[target_cols].astype(str)

代码说明

  1. df.replace(nested_dict):Pandas会自动识别嵌套字典的顶层键(即DataFrame的目标列名),对对应列中的值,用内层字典的键值对逐一替换。
  2. inplace=True:直接在原DataFrame上修改数据,无需重新赋值;若不想改动原数据,可删除该参数,将结果赋值给新变量(如new_df = df.replace(nested_dict))。
  3. 类型转换:由于嵌套字典的映射值是整数,而期望输出为字符串格式,因此通过astype(str)批量转换目标列的类型。如果不需要字符串格式,这一步可以省略。

验证结果

运行代码后,DataFrame将完全匹配你给出的期望输出:

Name tranchePatrimoineImmobilier tranchePatrimoineLiquidites tranchePatrimoineFinancier trancheRevenusReguliersNetsMensuels trancheCapaciteEpargneMensuelle
0   Tom                           1                           2                           2                                      2                                  3
1  Nick                           2                           2                           1                                      3                                  1
2  Juli                           3                           1                           3                                      1                                  2

内容的提问来源于stack exchange,提问作者Hugoz13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 13:05:10