如何通过方法链在Pandas中按列映射批量替换值?
Pandas方法链实现多列映射替换
问题描述
现有如下DataFrame:
col1 col2 col3 1 1 1 2 2 2 3 1 2 3 3 3
需要基于以下映射规则替换各列的数值:
- col1:
{1: 'dog', 2: 'cat', 3: 'bird'} - col2:
{1: 'yellow', 2: 'orange', 3: 'red'} - col3:
{1: 'dave', 2: 'pete', 3: 'tom'}
预期输出结果:
col1 col2 col3 dog yellow dave cat orange pete bird yellow pete bird red tom
已知Pandas的replace可以实现单列替换,但希望能像assign方法那样,通过方法链一次性传入多列的映射,伪代码如下:
# 伪代码 df.replace(col1=mapping1, col2=mapping2, col3=mapping3)
请问在Pandas中该如何实现?
解决方案
Pandas的replace函数天生就支持你想要的这种用法,直接传入一个以列名为键、对应映射字典为值的大字典就行,完全能实现方法链形式的多列批量替换:
完整代码示例
import pandas as pd # 构造原始DataFrame df = pd.DataFrame({ 'col1': [1, 2, 3, 3], 'col2': [1, 2, 1, 3], 'col3': [1, 2, 2, 3] }) # 定义各列的映射规则 column_mappings = { 'col1': {1: 'dog', 2: 'cat', 3: 'bird'}, 'col2': {1: 'yellow', 2: 'orange', 3: 'red'}, 'col3': {1: 'dave', 2: 'pete', 3: 'tom'} } # 方法链形式执行替换(可直接链式调用其他Pandas方法) result_df = df.replace(column_mappings) print(result_df)
运行结果
col1 col2 col3 0 dog yellow dave 1 cat orange pete 2 bird yellow pete 3 bird red tom
额外提示
- 若仅需替换部分列,只需在映射字典中保留对应列的规则即可,未指定的列会保持原始数据不变。
- 该写法完全适配方法链,你可以在
replace后直接衔接.drop()、.rename()等操作,无需拆分步骤。
内容的提问来源于stack exchange,提问作者Eisen
相关产品推荐
相关产品推荐

