rename() : rename columns and index keys

Pandas

DataFrame.rename(self, mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False, level=None, errors='ignore')
mapperDict to update the names along the axis.
indexSpecify index to rename
columnsDict to Specify columns to rename
axisAxis name or number ( 0, 1 ) to target the rename
inplaceBool, if set to True then original DataFrame changed
levelFor multiindex , rename is specified level.
errorsdefault 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 chaning 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()


plus2net.com



Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer