« Pandas
DataFrame.rename(self, mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False, level=None, errors='ignore')
mapper | Dict to update the names along the axis. |
index | Specify index to rename |
columns | Dict to Specify columns to rename |
axis | Axis name or number ( 0, 1 ) to target the rename |
inplace | Bool, if set to True then original DataFrame changed |
level | For multi Index , rename is specified level. |
errors | default is 'ignore', can be set to 'raise' |
Using columns option
We are trying to change the column NAME to name1
import pandas as pd
my_dict={'NAME':['Ravi','Raju','Alex','Ron','King','Jack'],
'ID':[1,2,3,4,5,6],'MATH':[30,40,50,60,70,80],
'ENGLISH':[20,30,40,50,60,70]}
my_data = pd.DataFrame(data=my_dict)
my_data1=my_data.rename(columns={'NAME':'name1','ENGLISH':'eng'})
print(my_data1)
Output
name1 ID MATH eng
0 Ravi 1 30 20
1 Raju 2 40 30
2 Alex 3 50 40
3 Ron 4 60 50
4 King 5 70 60
5 Jack 6 80 70
Using index and inplace options
In above code the original DataFrame is not changed. To update the original DataFrame we will use inplace=True
. Here we are changing the index keys ( first two , 0 and 1 )
my_data.rename(index={0:'a',1:'b'},inplace=True)
print(my_data)
Output
NAME ID MATH ENGLISH
a Ravi 1 30 20
b Raju 2 40 30
2 Alex 3 50 40
3 Ron 4 60 50
4 King 5 70 60
5 Jack 6 80 70
Using axis and function
We will change all column names to lower case char by using str.lower
. We will add axis=1
to our code.
my_data.rename(str.lower,axis=1,inplace=True)
print(my_data)
Output
name id math english
0 Ravi 1 30 20
1 Raju 2 40 30
2 Alex 3 50 40
3 Ron 4 60 50
4 King 5 70 60
5 Jack 6 80 70
« Pandas
columns() add_prefix() add_suffix()
← Subscribe to our YouTube Channel here