Python 如何从数据框中的所有列名/标题中删除数字

Python 如何从数据框中的所有列名/标题中删除数字,python,pandas,iteration,renaming,Python,Pandas,Iteration,Renaming,大家好,我有一个数据框,列名以“2018”结尾 我需要删除这些列名中的年份,我遇到了一些麻烦。我还需要从这些列名中去掉前导空格和尾随空格 我已经尝试了以下方法: df.columns.str.replace('\d+',"") #to try and remove the numbers from the column names df.columns = df.columns.str.strip('') #to try and get rid of the spaces df = df.r

大家好,我有一个数据框,列名以“2018”结尾

我需要删除这些列名中的年份,我遇到了一些麻烦。我还需要从这些列名中去掉前导空格和尾随空格

我已经尝试了以下方法:

df.columns.str.replace('\d+',"") #to try and remove the numbers from the column names

df.columns = df.columns.str.strip('') #to try and get rid of the spaces
df = df.rename(str.replace('\d+',""), axis='columns')
这些对数据帧没有任何影响

我希望列名称从“Stock 2018”改为“Stock”


但这并没有发生。谢谢你的帮助

您没有使用正确的方式重命名熊猫中的列:

从文档来看,您似乎可以简单地执行以下操作:

df.columns.str.replace('\d+',"") #to try and remove the numbers from the column names

df.columns = df.columns.str.strip('') #to try and get rid of the spaces
df = df.rename(str.replace('\d+',""), axis='columns')

让我知道这是否对您有效。

您只需要为删除数字指定
df.columns
,也不要向
str.strip()
传递任何内容来删除前导/尾随空格字符

df.columns=df.columns.str.replace('\d+','').str.strip()

您也可以尝试使用正则表达式

数据帧示例: 使用
regex的结果

你好我得到了一个TypeError“replace()至少接受2个参数(1个给定)给定的TypeError是什么,如果更简单的话,您可以使用粘贴箱进行回复