Python实现循环修改DataFrame列名:后缀数字转月份
Solution to Automatically Rename DataFrame Columns to Month Names
Here's a clean, scalable way to achieve your goal using Python's calendar module and pandas' column mapping:
Step 1: Import Required Modules
First, make sure you have pandas and the built-in calendar module imported:
import pandas as pd import calendar
Step 2: Define the Renaming Function
Create a helper function that checks each column name, extracts the trailing digit (if present), and maps it to the corresponding month name:
def convert_to_month(col_name): # Split the column name by underscores name_parts = col_name.split('_') # Check if the last segment is a numeric digit if name_parts[-1].isdigit(): # Convert the string digit to an integer month_number = int(name_parts[-1]) # Use calendar.month_name to get the full month name (1-indexed) return calendar.month_name[month_number] # For columns like 'Total', return the original name else: return col_name
Step 3: Apply the Function to Your DataFrame Columns
Use pandas' map() method to apply the function to all column names:
# Example DataFrame with your original columns df = pd.DataFrame(columns=['MCA036_LIFETIME_1', 'MCA036_LIFETIME_2', 'MCA036_LIFETIME_3', 'Total']) # Rename the columns df.columns = df.columns.map(convert_to_month) # Verify the result print(list(df.columns)) # Output: ['January', 'February', 'March', 'Total']
Alternative: Manual Month Mapping (No Calendar Module)
If you prefer not to use the calendar module, you can create a direct dictionary mapping for the digits you need:
month_mapping = { '1': 'January', '2': 'February', '3': 'March', # Add more entries for months 4-12 if needed } def convert_to_month_manual(col_name): name_parts = col_name.split('_') return month_mapping.get(name_parts[-1], col_name) # Apply the same way df.columns = df.columns.map(convert_to_month_manual)
Key Notes
- The
calendar.month_namelist is 1-indexed (socalendar.month_name[1]returns 'January'), which aligns perfectly with your column naming pattern. - This solution automatically handles any number of month columns (not just 3) as long as they follow the
*_digitformat. - Columns that don't match the pattern (like 'Total') are left unchanged, so you don't have to worry about excluding them manually.
内容的提问来源于stack exchange,提问作者Michael Ryan
相关产品推荐
相关产品推荐

