我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
当前回答
一个简单而“有趣”(和蟒蛇?)的解决方案:
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 = df.rename(columns=lambda x: x.replace('$', ''))
OR
df.rename(columns=lambda x: x.replace('$', ''), 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
列名与系列名称
我想解释一下幕后发生的事情。
数据帧是一组系列。
序列又是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']]
除了已经提供的解决方案之外,您还可以在读取文件时替换所有列。我们可以使用names和header=0来实现这一点。
首先,我们创建一个我们喜欢用作列名的名称列表:
import pandas as pd
ufo_cols = ['city', 'color reported', 'shape reported', 'state', 'time']
ufo.columns = ufo_cols
ufo = pd.read_csv('link to the file you are using', names = ufo_cols, header = 0)
在这种情况下,所有列名都将替换为列表中的名称。
我的方法是通用的,您可以通过逗号分隔分隔符=variable来添加额外的分隔符,并对其进行未来验证。
工作代码:
import pandas as pd
import re
df = pd.DataFrame({'$a':[1,2], '$b': [3,4],'$c':[5,6], '$d': [7,8], '$e': [9,10]})
delimiters = '$'
matchPattern = '|'.join(map(re.escape, delimiters))
df.columns = [re.split(matchPattern, i)[1] for i in df.columns ]
输出:
>>> df
$a $b $c $d $e
0 1 3 5 7 9
1 2 4 6 8 10
>>> df
a b c d e
0 1 3 5 7 9
1 2 4 6 8 10