Python Pandas 替换所有列名中的一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39741429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:38:51  来源:igfitidea点击:

Pandas replace a character in all column names

pythonpandas

提问by Cedric H.

I have data frames with column names (coming from .csv files) containing (and )and I'd like to replace them with _.

我有列名的数据帧包含(从.csv档案来推出)()我想,以取代他们_

How can I do that in place for all columns?

我怎样才能为所有列做到这一点?

回答by jezrael

Use str.replace:

使用str.replace

df.columns = df.columns.str.replace("[()]", "_")

Sample:

样本:

df = pd.DataFrame({'(A)':[1,2,3],
                   '(B)':[4,5,6],
                   'C)':[7,8,9]})

print (df)
   (A)  (B)  C)
0    1    4   7
1    2    5   8
2    3    6   9

df.columns = df.columns.str.replace(r"[()]", "_")
print (df)
   _A_  _B_  C_
0    1    4   7
1    2    5   8
2    3    6   9

回答by agbalutemi

The square brackets are used to demarcate a range of characters you want extracted. for example:

方括号用于划分要提取的字符范围。例如:

r"[Nn]ational"

will extract both occurences where we have "National" and "national" i.e it extracts N or n.

将提取我们有“国家”和“国家”的两个出现,即它提取 N 或 n。