How to Rename pandas columns | pandas.DataFrame.rename function

Spread the love

If you want rename for columns in pandas, you have to use the inbuild pandas function pandas.DataFrame.rename function().

Syntax:  DataFrame.rename(mapper=None, index=None, columns=None, axis=None, copy=True, inplace=False, level=None)
Alter axes labels.

Function / dict values must be unique (1-to-1). Labels not contained in a dict / Series will be left as-is. Extra labels listed don’t throw an error.

mapper, index, columns : dict-like or function, optional
dict-like or functions transformations to apply to that axis’ values. Use either mapper and axis to specify the axis to target with mapper, or index and columns.

axis : int or str, optional
Axis to target with mapper. Can be either the axis name (‘index’, ‘columns’) or number (0, 1). The default is ‘index’.

copy : boolean, default True
Also copy underlying data

inplace : boolean, default False
Whether to return a new DataFrame. If True then value of copy is ignored.

level : int or level name, default None
In case of a MultiIndex, only rename labels in the specified level.

renamed : DataFrame

# example program on how to rename pandas columns

import pandas as pd df = pd.DataFrame({"X": [1, 2, 3], "Y": [20000, 25000, 30000]}) print(df) df =df.rename(index=str, columns={"X": "exp", "Y": "salary"}) print(df)


   X      Y
0  1  20000
1  2  25000
2  3  30000
   exp  salary
0    1   20000
1    2   25000
2    3   30000



Leave a Reply

Your email address will not be published. Required fields are marked *