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

如何在Pandas/Python中批量移除DataFrame列名的特殊字符?

一次性移除Pandas列名中的所有特殊字符

针对你的场景,无需多次调用replace,可以用正则表达式结合字符串方法批量处理列名:

import pandas as pd

# 示例DataFrame
data = {
    "('Untitled 1, Year')": [2000, 2001],
    "('Untitled 1', 'Name')": ['John', 'Kelly'],
    "('Life', 'Age')": [24, 32]
}
df = pd.DataFrame(data)

# 处理列名
df.columns = df.columns.str.replace(',', ' ') \
                         .str.replace(r'[^\w\s]', '', regex=True) \
                         .str.replace(r'\s+', ' ', regex=True)

print(df)

代码说明:

  • 第一步str.replace(',', ' '):把列名中的逗号替换为空格,避免直接删除逗号导致文本粘连;
  • 第二步str.replace(r'[^\w\s]', '', regex=True):移除所有非字母、数字、空格的特殊字符(比如括号、单引号等);
  • 第三步str.replace(r'\s+', ' ', regex=True):将多个连续空格合并为单个空格,保证列名格式整洁。

运行后输出结果:

Untitled 1 Year  Untitled 1 Name  Life Age
0             2000             John       24
1             2001            Kelly       32

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:15:05