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 | set_axis 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's DataFrame.set_axis(~) method assigns a new label to the source DataFrame's columns or index.

Parameters

1. labels | list-like or index

The new column or index labels.

2. axis | string or int | optional

Whether to set a new column label or an index label:

Axis

Description

Set new row labels

0 or "index"

Set new column labels

1 or "columns"

By default, axis=0.

3. inplace | boolean | optional

Whether or not to perform the method in-place:

  • If True, then the source DataFrame will be directly modified, and no new DataFrame will be created.

  • If False, then a new DataFrame is created and returned.

By default, inplace=False.

Return value

A DataFrame with either new column or index labels. Note that if inplace=True, then nothing is returned since the source DataFrame is directly modified.

Examples

Consider the following DataFrame:

df = pd.DataFrame({"A":[3,4],"B":[5,6]})
df
A B
0 3 5
1 4 6

Setting new index labels using a list

To assign new index labels (i.e. row labels) using a list:

df.set_axis(["a","b"])
A B
a 3 5
b 4 6

Setting new index labels using Index object

To assign new index labels (i.e. row labels) using an index object:

index_date = pd.date_range("2020-12-25", periods=2)
df.set_axis(index_date)
A B
2020-12-25 3 5
2020-12-26 4 6

Here, we are assigning a DateTime Index.

Setting new column labels

To assign new column labels, set axis=1:

df.set_axis(["C","D"], axis=1)
C D
0 3 5
1 4 6
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...
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!