我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
我想从
['$a', '$b', '$c', '$d', '$e']
to
['a', 'b', 'c', 'd', 'e']
当前回答
除了已经提供的解决方案之外,您还可以在读取文件时替换所有列。我们可以使用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)
在这种情况下,所有列名都将替换为列表中的名称。
其他回答
许多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代码。
另一种替换原始列标签的方法是从原始列标签中删除不需要的字符(此处为“$”)。
这可以通过在df.columns上运行for循环并将剥离的列附加到df.column来完成。
相反,我们可以通过使用下面的列表理解在一个语句中巧妙地做到这一点:
df.columns = [col.strip('$') for col in df.columns]
(Python中的strip方法会从字符串的开头和结尾剥离给定的字符。)
假设您的数据集名称为df,df具有。
df = ['$a', '$b', '$c', '$d', '$e']`
所以,要重命名这些,我们只需这样做。
df.columns = ['a','b','c','d','e']
重命名方法可以采用一个函数,例如:
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)
# This way it will work
import pandas as pd
# Define a dictionary
rankings = {'test': ['a'],
'odi': ['E'],
't20': ['P']}
# Convert the dictionary into DataFrame
rankings_pd = pd.DataFrame(rankings)
# Before renaming the columns
print(rankings_pd)
rankings_pd.rename(columns = {'test':'TEST'}, inplace = True)