我想从
['$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)
其他回答
另一种替换原始列标签的方法是从原始列标签中删除不需要的字符(此处为“$”)。
这可以通过在df.columns上运行for循环并将剥离的列附加到df.column来完成。
相反,我们可以通过使用下面的列表理解在一个语句中巧妙地做到这一点:
df.columns = [col.strip('$') for col in df.columns]
(Python中的strip方法会从字符串的开头和结尾剥离给定的字符。)
请注意,前面答案中的方法不适用于MultiIndex。对于MultiIndex,您需要执行以下操作:
>>> df = pd.DataFrame({('$a','$x'):[1,2], ('$b','$y'): [3,4], ('e','f'):[5,6]})
>>> df
$a $b e
$x $y f
0 1 3 5
1 2 4 6
>>> rename = {('$a','$x'):('a','x'), ('$b','$y'):('b','y')}
>>> df.columns = pandas.MultiIndex.from_tuples([
rename.get(item, item) for item in df.columns.tolist()])
>>> df
a b e
x y f
0 1 3 5
1 2 4 6
由于您只想删除所有列名中的$符号,因此只需执行以下操作:
df = df.rename(columns=lambda x: x.replace('$', ''))
OR
df.rename(columns=lambda x: x.replace('$', ''), inplace=True)
如果已经有新列名的列表,可以尝试以下操作:
new_cols = ['a', 'b', 'c', 'd', 'e']
new_names_map = {df.columns[i]:new_cols[i] for i in range(len(new_cols))}
df.rename(new_names_map, axis=1, inplace=True)
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]