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

动态重命名DataFrame中含中间数字的列名

Alright, let's solve this column renaming task for your DataFrame. Here's a clean, dynamic solution using regex that handles exactly what you need: moving middle underscore-number segments to the end, while leaving trailing ones untouched.

Step 1: Break Down the Pattern

First, let's clarify which columns need changes and which don't:

  • Needs renaming: Columns where _X (X is a number) sits in the middle, followed by more characters (e.g., Action_3.@source, Description_3.#text)
  • Stays as-is: Columns where _X is at the very end (e.g., Animal_1, Car_2)

Step 2: The Regex & Renaming Function

We'll use a regex pattern to capture the parts of the column name, then rearrange them only if the number segment isn't at the end. Here's the complete function to fill your TODO:

import pandas as pd
import re

def reformat_column_name(col):
    # Regex to split the column into [prefix]_[number][suffix]
    match = re.match(r'^(.*)_(\d+)(.*)$', col)
    if match:
        prefix, num, suffix = match.groups()
        # Only rearrange if there's content after the number (suffix isn't empty)
        if suffix:
            return f"{prefix}{suffix}_{num}"
        # If suffix is empty, the number is already at the end—keep original name
        return col
    # Columns without underscore-number patterns stay unchanged
    return col

Step 3: Apply to Your DataFrame

Use map() to apply this function across all your DataFrame's columns:

# Example DataFrame to test the logic
df = pd.DataFrame({
    'Action_3.@source': [1, 2, 3],
    'Description_3.#text': ['foo', 'bar', 'baz'],
    'Animal_1': ['cat', 'dog', 'bird'],
    'Status_4.status_code': [200, 404, 500],
    'Book_7': ['1984', 'Dune', 'Foundation']
})

# Rename the columns
df.columns = df.columns.map(reformat_column_name)

# Verify the result
print(df.columns)
# Output: Index(['Action.@source_3', 'Description.#text_3', 'Animal_1', 'Status.status_code_4', 'Book_7'], dtype='object')

How It Works

  • The regex ^(.*)_(\d+)(.*)$ splits the column name into three groups: everything before the last _X, the number X, and everything after X.
  • If the third group (suffix) isn't empty, we know the number is in the middle—so we combine prefix + suffix + _num to shift the number to the end.
  • If the suffix is empty, the number is already at the end, so we leave the column name as-is.
  • Columns that don't match the underscore-number pattern (like User_FullName) are returned unchanged.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 15:22:31