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

如何重命名Pandas DataFrame列名:FY18Qn改1Q18、FY18YearTotal改FY18

Pandas列名重命名解决方案

方法一:字典映射(直观可靠)

直接构建原列名到目标列名的映射字典,通过rename()方法完成重命名,适合列名数量不多的场景:

import pandas as pd

df = pd.DataFrame({ 
'FY18Q1': [ 1500, 1200, 950, 2200], 
'FY18Q2': [ 2340, 1234, 2000, 1230],
'FY18Q3': [2130, 2200, 2190, 2210],   
'FY18YearTotal': [1000, 1900, 1500, 1800]})

# 定义列名映射关系
col_mapping = {
    'FY18Q1': '1Q18',
    'FY18Q2': '2Q18',
    'FY18Q3': '3Q18',
    'FY18YearTotal': 'FY18'
}

# 执行重命名
df = df.rename(columns=col_mapping)
print(df.columns)
# 输出: Index(['1Q18', '2Q18', '3Q18', 'FY18'], dtype='object')

方法二:正则批量替换(适配同格式列名)

如果后续还有同格式的列名(比如FY19Q1、FY19YearTotal),可以用正则表达式批量处理两种列名格式:

import pandas as pd

df = pd.DataFrame({ 
'FY18Q1': [ 1500, 1200, 950, 2200], 
'FY18Q2': [ 2340, 1234, 2000, 1230],
'FY18Q3': [2130, 2200, 2190, 2210],   
'FY18YearTotal': [1000, 1900, 1500, 1800]})

# 处理季度列:调换年份和季度的位置
df.columns = df.columns.str.replace(r'FY(\d{2})Q(\d)', r'\2Q\1', regex=True)
# 处理年度总列:移除YearTotal后缀
df.columns = df.columns.str.replace(r'FY(\d{2})YearTotal', r'FY\1', regex=True)

print(df.columns)
# 输出: Index(['1Q18', '2Q18', '3Q18', 'FY18'], dtype='object')

正则逻辑说明:

  • 针对FY18Q1:正则FY(\d{2})Q(\d)捕获年份18和季度1,替换为\2Q\1实现位置调换
  • 针对FY18YearTotal:正则FY(\d{2})YearTotal捕获年份18,替换为FY\1保留年份前缀

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 04:07:14