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

Python中基于字典值匹配,用字典键重命名DataFrame列

实现列名替换方案

原数据定义

import pandas as pd

df = pd.DataFrame({'a':[1,2,3,4], 'x':[11,12,13,14]})
dict_ = {'new_a':['a','b','c'],'new_x':['x','y','z']} 

步骤1:构建值到键的映射字典

原字典结构为新列名: [原列名1, 原列名2, ...],我们需要反转映射关系,得到原列名: 新列名的结构,方便快速匹配替换:

reverse_map = {val: key for key, vals in dict_.items() for val in vals}

执行后reverse_map内容为:{'a': 'new_a', 'b': 'new_a', 'c': 'new_a', 'x': 'new_x', 'y': 'new_x', 'z': 'new_x'}

步骤2:重命名DataFrame列

使用pandas.DataFrame.rename()方法,传入映射字典即可自动替换匹配的列名,未匹配的列会保持原样:

df = df.rename(columns=reverse_map)

最终结果

执行后df的结构如下:

print(df)
# 输出:
#    new_a  new_x
# 0      1     11
# 1      2     12
# 2      3     13
# 3      4     14

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 10:15:40