我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
当前回答
重命名特定列
使用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
其他回答
许多panda函数都有一个就地参数。当设置为True时,转换将直接应用于调用它的数据帧。例如:
df = pd.DataFrame({'$a':[1,2], '$b': [3,4]})
df.rename(columns={'$a': 'a'}, inplace=True)
df.columns
>>> Index(['a', '$b'], dtype='object')
或者,在某些情况下,您希望保留原始数据帧。如果创建数据帧是一项昂贵的任务,我经常看到人们陷入这种情况。例如,如果创建数据帧需要查询雪花数据库。在这种情况下,只需确保将inplace参数设置为False。
df = pd.DataFrame({'$a':[1,2], '$b': [3,4]})
df2 = df.rename(columns={'$a': 'a'}, inplace=False)
df.columns
>>> Index(['$a', '$b'], dtype='object')
df2.columns
>>> Index(['a', '$b'], dtype='object')
如果这些类型的转换是您经常做的,那么您还可以研究一些不同的panda GUI工具。我是一个叫做水户的人的创造者。它是一个电子表格,可以自动将您的编辑转换为python代码。
可以将lstrip或strip方法与索引一起使用:
df.columns = df.columns.str.lstrip('$')
or
cols = ['$a', '$b', '$c', '$d', '$e']
pd.Series(cols).str.lstrip('$').tolist()
输出:
['a', 'b', 'c', 'd', 'e']
df = pd.DataFrame({'$a': [1], '$b': [1], '$c': [1], '$d': [1], '$e': [1]})
如果新列列表的顺序与现有列的顺序相同,则分配很简单:
new_cols = ['a', 'b', 'c', 'd', 'e']
df.columns = new_cols
>>> df
a b c d e
0 1 1 1 1 1
如果您有一个将旧列名键入到新列名的字典,可以执行以下操作:
d = {'$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}
df.columns = df.columns.map(lambda col: d[col]) # Or `.map(d.get)` as pointed out by @PiRSquared.
>>> df
a b c d e
0 1 1 1 1 1
如果你没有列表或字典映射,你可以通过列表理解去掉前导$符号:
df.columns = [col[1:] if col[0] == '$' else col for col in df]
您可以使用str.slice:
df.columns = df.columns.str.slice(1)
重命名方法可以采用一个函数,例如:
In [11]: df.columns
Out[11]: Index([u'$a', u'$b', u'$c', u'$d', u'$e'], dtype=object)
In [12]: df.rename(columns=lambda x: x[1:], inplace=True)
In [13]: df.columns
Out[13]: Index([u'a', u'b', u'c', u'd', u'e'], dtype=object)