Python | Pandas Series.set_axis ()

Python Methods and Functions

Series.set_axis() Pandas Series.set_axis() is used to assign the desired index to a given axis. Indexes for column or row labels can be changed by assigning a list or index.

Syntax: Series.set_axis (labels, axis = 0, inplace = None)

Parameter:
labels: The values ​​for the new index.
axis: The axis to update ... The value 0 identifies the rows, and 1 identifies the columns.
inplace: Whether to return a new% (klass) s instance.

Returns: renamed: series

Example # 1: Use Series.set_axis () to reset the axis of this Series object.

# import pandas as pd

import pandas as pd

 
# Create a series

sr = pd.Series ([ `New York` , ` Chicago` , ` Toronto` , `Lisbon` , `Rio` , `Moscow` ])

  
# Create index

index_ = [ ` City 1` , `City 2` , `City 3` , ` City 4` , `City 5` , `City 6` ]

  
# set index

sr.index = index_

 
# Print series

print (sr)

Output:

Now we will use Series.set_axis () to reset the index of this series object

# Create Index

didx = pd.DatetimeIndex (start = `2014-08-01 10: 00` , freq = ` W`

periods = 6 , tz = `Europe / Berlin`

 

 
# reset index

sr.set_axis (didx, inplace = True )

 
# Print series

print (sr)

Output:

As we see in the output, Series.set_axis () successfully reset the index of this Series object.

Example # 2: Use Series.set_axis () to reset the axis of this object Series.

# import pandas as pd

import pandas as pd

 
# Create series

sr = pd.Series ([ 100 , 25 , 32 , 118 , 24 , 65 ])

 
# Print series

print (sr)

Output:

We will now use Series.set_axis () to reset the index of this series object

# Assign a new index

sr.set_axis ([ `A` , ` B` , `C` , ` D` , `E` , ` F` ], inplace = True )

 
# p print series

print (sr)

Output:

As we can see in the output, Series.set_axis () successfully reset the index of this Series object.





Get Solution for free from DataCamp guru