search
Search
Join our weekly DS/ML newsletter layers DS/ML Guides
menu
menu search toc more_vert
Robocat
Guest 0reps
Thanks for the thanks!
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
help Ask a question
Share on Twitter
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to
A
A
brightness_medium
share
arrow_backShare
Twitter
Facebook

Pandas DataFrame | rename method

Pandas
chevron_right
Documentation
chevron_right
DataFrame
chevron_right
Data Selection and Renaming
schedule Jul 1, 2022
Last updated
local_offer PythonPandas
Tags

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 = pd.DataFrame({"A":[1,2], "B":[3,4]})
df
   A  B
0  1  3
1  2  4

Renaming a single column

To rename column "A" to "C":

df.rename(columns={"A":"C"})
   C  B
0  1  3
1  2  4

Renaming multiple columns

To rename columns "A" and "B" to "C" and "D", respectively:

df.rename(columns={"A":"C", "B":"D"})
   C  D
a  1  3
b  2  4

Renaming indices

Consider the same DataFrame, df, as before:

df
   A  B
0  1  3
1  2  4

Renaming a single index

To rename the index 0 to "a":

df.rename(index={0:"a"})
   A  B
a  1  3
1  2  4

Renaming multiple indices

To rename multiple indices:

df.rename(index={0:"a", 1:"b"})
   A  B
a  1  3
b  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:

df = pd.DataFrame({"A":[1,2], "B":[3,4]})
df.rename(columns={"A":"C"}, inplace=True)
df
C B
0 1 3
1 2 4

Here, we've modified our df directly.

mail
Join our newsletter for updates on new DS/ML comprehensive guides (spam-free)
robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
Ask a question or leave a feedback...