我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
当前回答
重命名Pandas中的列是一项简单的任务。
df.rename(columns={'$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}, inplace=True)
其他回答
只需将其分配给.columns属性:
>>> df = pd.DataFrame({'$a':[1,2], '$b': [10,20]})
>>> df
$a $b
0 1 10
1 2 20
>>> df.columns = ['a', 'b']
>>> df
a b
0 1 10
1 2 20
一个简单而“有趣”(和蟒蛇?)的解决方案:
df.rename(columns={x: x.replace('$', '') for x in df.columns})
哪里:
df = pd.DataFrame(columns=['$a', '$b', '$c', '$d', '$e'])
步骤:
获取DataFrame的列作为列表:
df.columns
在DataFrames中重命名的方法:
df.rename()
属性以指定要重命名列:
columns={}
在字典中,您需要指定要重命名的列(在每个键中)以及它们将获得的新名称(每个值)
{'old_col_name': 'new_col_name', ...}
由于您的更改遵循一种模式,为了删除每列中的$字符,我们可以使用字典理解:
{x: x.replace('$', '') for x in df.columns}
重命名特定列
使用df.reame()函数并引用要重命名的列。并非所有列都必须重命名:
df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})
# Or rename the existing DataFrame (rather than creating a copy)
df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)
最小代码示例
df = pd.DataFrame('x', index=range(3), columns=list('abcde'))
df
a b c d e
0 x x x x x
1 x x x x x
2 x x x x x
以下方法都可以工作并产生相同的输出:
df2 = df.rename({'a': 'X', 'b': 'Y'}, axis=1) # new method
df2 = df.rename({'a': 'X', 'b': 'Y'}, axis='columns')
df2 = df.rename(columns={'a': 'X', 'b': 'Y'}) # old method
df2
X Y c d e
0 x x x x x
1 x x x x x
2 x x x x x
请记住将结果指定回,因为修改不在原位。或者,指定inplace=True:
df.rename({'a': 'X', 'b': 'Y'}, axis=1, inplace=True)
df
X Y c d e
0 x x x x x
1 x x x x x
2 x x x x x
在v0.25中,如果指定了要重命名的无效列,还可以指定errors='raise'来引发错误。请参阅v0.25 rename()文档。
重新分配列标题
使用df.set_axis(),axis=1,inplace=False(返回副本)。
df2 = df.set_axis(['V', 'W', 'X', 'Y', 'Z'], axis=1, inplace=False)
df2
V W X Y Z
0 x x x x x
1 x x x x x
2 x x x x x
这将返回一个副本,但您可以通过设置inplace=True来修改DataFrame(这是<=0.24版本的默认行为,但将来可能会更改)。
您也可以直接分配标题:
df.columns = ['V', 'W', 'X', 'Y', 'Z']
df
V W X Y Z
0 x x x x x
1 x x x x x
2 x x x x x
重命名Pandas中的列是一项简单的任务。
df.rename(columns={'$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}, inplace=True)
假设您可以使用正则表达式,则此解决方案无需使用正则表达式进行手动编码:
import pandas as pd
import re
srch = re.compile(r"\w+")
data = pd.read_csv("CSV_FILE.csv")
cols = data.columns
new_cols = list(map(lambda v:v.group(), (list(map(srch.search, cols)))))
data.columns = new_cols