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

Python脚本:如何在rename方法中结合全局变量与.format()动态改列名

Dynamic Column Renaming for Quarterly PDF Reports in Python

Absolutely! Using global variables combined with string formatting is a perfect way to eliminate hardcoded column names and make your script run seamlessly every quarter without manual edits. Here's a step-by-step breakdown of how to implement this:

1. Define Global Configuration Variables

First, set up global variables to capture the target quarter and year. You can either manually configure them for specific runs, or automate the process to pull the current quarter dynamically using Python's datetime module:

# Option 1: Manual configuration for a specific quarter
TARGET_YEAR = 2024
TARGET_QUARTER = "Q3"

# Option 2: Auto-detect current quarter (fully hands-off)
from datetime import datetime

current_date = datetime.now()
TARGET_YEAR = current_date.year
TARGET_QUARTER = f"Q{(current_date.month - 1) // 3 + 1}"

2. Create a Dynamic Column Mapping Template

Instead of hardcoding each column name, use a dictionary with placeholders that will be filled in using string formatting. This keeps your mapping flexible and easy to update:

# Base template with placeholders for year/quarter
COLUMN_MAPPING_TEMPLATE = {
    'VP_x': 'VP',
    '{year} {quarter} Target Hours': 'hourTarget{year_short}{quarter}'
}

# Generate the final mapping by replacing placeholders
year_short = str(TARGET_YEAR)[-2:]  # Get last two digits (e.g., 24 for 2024)
column_mapping = {
    key.format(year=TARGET_YEAR, quarter=TARGET_QUARTER): 
    value.format(year_short=year_short, quarter=TARGET_QUARTER)
    for key, value in COLUMN_MAPPING_TEMPLATE.items()
}

3. Apply the Dynamic Mapping to rename()

Now pass the generated column_mapping to your rename() method—no more hardcoded quarter values!

Target_Hours_All.rename(columns=column_mapping, inplace=True)

Bonus: Reusable Function for Multiple Datasets

If you need to apply this logic across multiple datasets, wrap the mapping generation in a reusable function. This ensures consistency and simplifies future updates:

def generate_column_mapping(year, quarter):
    year_short = str(year)[-2:]
    return {
        'VP_x': 'VP',
        f'{year} {quarter} Target Hours': f'hourTarget{year_short}{quarter}'
        # Add other column patterns here as needed
    }

# Usage for the current quarter
current_mapping = generate_column_mapping(TARGET_YEAR, TARGET_QUARTER)
Target_Hours_All.rename(columns=current_mapping, inplace=True)
# Repeat for other datasets with the same function call

This approach not only removes the need for manual edits each quarter but also makes your code more readable and maintainable. If you ever need to adjust the naming pattern, you only have to update the template in one place instead of hunting through multiple hardcoded lines.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:07:50