![](/img/trans.png)
[英]How do I remove numbers and/or parenthesis from names in a DataFrame column
[英]How to remove numbers from all column names / headers in a dataframe
嗨,所以我有一个数据框,其列名以'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
这些对数据框没有任何作用。
我希望列名称从“ Stock 2018”更改为“ Stock”
但这没有发生。 感谢您的帮助!
您没有使用重命名熊猫中列的正确方法: https : //pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html
从文档看来,您可以简单地执行以下操作:
df = df.rename(str.replace('\d+',""), axis='columns')
让我知道这是否适合您。
您只需要分配给df.columns
删除数字,也无需将任何内容传递给str.strip()
即可删除前导/后缀空格字符。
df.columns=df.columns.str.replace('\d+','').str.strip()
您也可以尝试使用正则表达式。
>>> df = pd.DataFrame.from_dict({'Name04': ['Chris', 'Joe', 'Karn', 'Alina'], 'Age04': [14, 16, 18, 21], 'Weight04': [15, 21, 37, 45]})
>>> df
Age04 Name04 Weight04
0 14 Chris 15
1 16 Joe 21
2 18 Karn 37
3 21 Alina 45
regex
结果: >>> df.columns = df.columns.str.replace(r'\d+', '')
>>> df
Age Name Weight
0 14 Chris 15
1 16 Joe 21
2 18 Karn 37
3 21 Alina 45
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.