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

如何在Pandas中按顺序重命名重复的列名

你之前使用df.rename()传入重复key的字典无法实现需求,原因是Python字典的key具备唯一性,重复定义的同名key会被后定义的内容覆盖,无法对应到多个同名列。

通用解决方法(适配任意数量、任意类型的重复列名)

from collections import defaultdict
import pandas as pd

# 此处替换为你自己的DataFrame初始化逻辑
df = pd.DataFrame([[1,1,2]], columns=['DD', 'Nice', 'Nice', 'Hello'])

col_count = defaultdict(int)
new_columns = []
for col in df.columns:
    col_count[col] += 1
    # 仅对出现超过1次的列追加序号
    new_columns.append(f"{col}{col_count[col]}" if col_count[col] > 1 else col)

df.columns = new_columns

执行后df的列名将自动更新为['DD', 'Nice1', 'Nice2', 'Hello'],符合预期效果。

针对性处理方案(仅处理指定的重复列)

如果你确认只有Nice列存在重复,可以用更简单的写法:

# 定位所有名为Nice的列的位置
nice_pos = [idx for idx, col_name in enumerate(df.columns) if col_name == 'Nice']
# 按顺序追加序号
for i, pos in enumerate(nice_pos, start=1):
    df.columns.values[pos] = f"Nice{i}"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:36:01