Pandas DataFrame | rename method
Start your free 7-days trial now!
Pandas' DataFrame.rename(~) method renames the columns and indexes of the DataFrame.
Parameters
1. columnslink | dict
A dictionary whose keys are the column names you want to modify, and values are the new column names.
2. indexlink | dict
A dictionary whose keys are the index names you want to modify, and values are the new index names.
3. inplacelink | boolean | optional
If
True, then modify and return the source DataFrame without creating a new one.If
False, then a new DataFrame is returned.
By default, inplace=False.
Return Value
A DataFrame with its columns or indexes renamed.
Examples
Renaming columns
Consider the following DataFrame:
df
A B0 1 31 2 4
Renaming a single column
To rename column "A" to "C":
df.rename(columns={"A":"C"})
C B0 1 31 2 4
Renaming multiple columns
To rename columns "A" and "B" to "C" and "D", respectively:
df.rename(columns={"A":"C", "B":"D"})
C Da 1 3b 2 4
Renaming indices
Consider the same DataFrame, df, as before:
df
A B0 1 31 2 4
Renaming a single index
To rename the index 0 to "a":
df.rename(index={0:"a"})
A Ba 1 31 2 4
Renaming multiple indices
To rename multiple indices:
df.rename(index={0:"a", 1:"b"})
A Ba 1 3b 2 4
Here, we've renamed column 0 to "a", and column 1 to "b".
Perform renaming in-place
By default, inplace=False, which means that the method returns an entirely new DataFrame without modifying the source DataFrame.
To directly modify the source DataFrame instead, set inplace=True like so:
C B0 1 31 2 4
Here, we've modified our df directly.