我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
当前回答
可以将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']
其他回答
另一个选项是使用正则表达式重命名:
import pandas as pd
import re
df = pd.DataFrame({'$a':[1,2], '$b':[3,4], '$c':[5,6]})
df = df.rename(columns=lambda x: re.sub('\$','',x))
>>> df
a b c
0 1 3 5
1 2 4 6
如果您只想删除“$”符号,请使用以下代码
df.columns = pd.Series(df.columns.str.replace("$", ""))
我的单线回答是
df.columns=df_new_cols
它是最好的,处理时间为1/3。
timeit比较:
df有七列。我正在尝试更改一些名称。
%timeit df.rename(columns={old_col:new_col for (old_col,new_col) in zip(df_old_cols,df_new_cols)},inplace=True)
214 µs ± 10.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit df.rename(columns=dict(zip(df_old_cols,df_new_cols)),inplace=True)
212 µs ± 7.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit df.columns = df_new_cols
72.9 µs ± 17.2 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
df.columns = ['a', 'b', 'c', 'd', 'e']
它将按照您提供的顺序用您提供的名称替换现有名称。
列名与系列名称
我想解释一下幕后发生的事情。
数据帧是一组系列。
序列又是numpy.array的扩展。
numpy.arrays具有属性.name。
这是系列的名称。熊猫很少尊重这个属性,但它会在某些地方停留,可以用来攻击熊猫的一些行为。
命名列列表
这里有很多答案谈到df.columns属性是一个列表,而实际上它是一个系列。这意味着它具有.name属性。
如果您决定填写列的名称“系列:
df.columns = ['column_one', 'column_two']
df.columns.names = ['name of the list of columns']
df.index.names = ['name of the index']
name of the list of columns column_one column_two
name of the index
0 4 1
1 5 2
2 6 3
请注意,索引的名称总是低一列。
挥之不去的艺术事实
.name属性有时会持续存在。如果将df.columns设置为['one','two'],则df.one.name将为'one'。
如果您将df.one.name设置为'three',则df.columns仍然会给您['one','two'],df.one.name会给您'three]。
BUT
pd.DataFrame(df.one)将返回
three
0 1
1 2
2 3
因为Pandas重用已经定义的Series的.name。
多级列名
Pandas有多种方法来实现多层列名。这里面没有太多魔法,但我想在我的回答中也包括这一点,因为我没有看到任何人在这里学习这一点。
|one |
|one |two |
0 | 4 | 1 |
1 | 5 | 2 |
2 | 6 | 3 |
通过将列设置为列表,这很容易实现,如下所示:
df.columns = [['one', 'one'], ['one', 'two']]