Renaming columns in pandas

2018-12-31 04:37发布

I have a DataFrame using pandas and column labels that I need to edit to replace the original column labels.

I'd like to change the column names in a DataFrame A where the original column names are:

['$a', '$b', '$c', '$d', '$e'] 

to

['a', 'b', 'c', 'd', 'e'].

I have the edited column names stored it in a list, but I don't know how to replace the column names.

28条回答
墨雨无痕
2楼-- · 2018-12-31 05:21

Note that these approach do not work for a MultiIndex. For a MultiIndex, you need to do something like the following:

>>> 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
查看更多
有味是清欢
3楼-- · 2018-12-31 05:22

The rename dataframe columns and replace format

import pandas as pd

data = {'year':[2015,2011,2007,2003,1999,1996,1992,1987,1983,1979,1975],
        'team':['Australia','India','Australia','Australia','Australia','Sri Lanka','Pakistan','Australia','India','West Indies','West Indies'],
        }
df = pd.DataFrame(data)

#Rename Columns
df.rename(columns={'year':'Years of Win','team':'Winning Team'}, inplace=True)

#Replace format
df = df.columns.str.replace(' ', '_')
查看更多
像晚风撩人
4楼-- · 2018-12-31 05:23
旧人旧事旧时光
5楼-- · 2018-12-31 05:25

Another option is to rename using a regular expression:

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
查看更多
栀子花@的思念
6楼-- · 2018-12-31 05:26
df.columns = ['a', 'b', 'c', 'd', 'e']

It will replace the existing names with the names you provide, in the order you provide.

查看更多
无与为乐者.
7楼-- · 2018-12-31 05:26

df = df.rename(columns=lambda n: n.replace('$', '')) is a functional way of solving this

查看更多
登录 后发表回答