w3resource

Pandas Series: set_axis() function

Series-set_axis() function

The set_axis() function is used to assign desired index to given axis.
Indexes for column or row labels can be changed by assigning a list-like or Index.
Changed in version 0.21.0: The signature is now labels and axis, consistent with the rest of pandas API. Previously, the axis and labels arguments were respectively the first and second positional arguments.

Syntax:

Series.set_axis(self, labels, axis=0, inplace=None)
Pandas Series set_axis image

Parameters:

Name Description Type/Default Value Required / Optional
labels The values for the new index. list-like, Index Required
axis The axis to update. The value 0 identifies the rows, and 1 identifies the columns. {0 or ‘index’, 1 or ‘columns’}
Default Value: 0
Required
inplace Whether to return a new %(klass)s instance. bool
Default Value: None
Required

Returns: renamed - %(klass)s or None An object of same type as caller if inplace=False, None otherwise.

Example - Series:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series([2, 3, 4])
s

Output:

0    2
1    3
2    4
dtype: int64
Pandas Series set_axis image

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series([2, 3, 4])
s.set_axis(['p', 'q', 'r'], axis=0, inplace=False)

Output:

p    2
q    3
r    4
dtype: int64

Example - The original object is not modified:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series([2, 3, 4])
s

Output:

0    2
1    3
2    4
dtype: int64

DataFrame

Example - Change the row labels:

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame({"X": [2, 3, 4], "Y": [5, 6, 7]})
df.set_axis(['p', 'q', 'r'], axis='index', inplace=False)

Output:

  X	  Y
p	 2	  5
q	 3	  6
r	 4	  7

Example - Change the column labels:

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame({"X": [2, 3, 4], "Y": [5, 6, 7]})
df.set_axis(['I', 'II'], axis='columns', inplace=False)

Output:

  I	 II
0	2	5
1	3	6
2	4	7

Example - Now, update the labels inplace:

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame({"X": [2, 3, 4], "Y": [5, 6, 7]})
df.set_axis(['i', 'ii'], axis='columns', inplace=True)
df

Output:

   i  ii
0  2   5
1  3   6
2  4   7

Previous: Random items from an axis of Pandas object
Next: Series-take() function



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/pandas/series/series-set_axis.php