search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
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

Pandas DataFrame | rename method

schedule Aug 12, 2023
Last updated
local_offer
PythonPandas
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
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 = 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.

robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...