Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.index attribute is used to get or set the index labels of the given Series object.
Pandas Series Index() Methods
Syntax: Series.index()
Returns : index
Pandas Series Index Example
Use Series.index attribute to set the index label for the given Series object.
Python3
# importing pandas as pd import pandas as pd # Creating the Series series = pd.Series([ 'New York' , 'Chicago' , 'Toronto' , 'Lisbon' ]) # Print the series print (series) |
Output:
0 New York 1 Chicago 2 Toronto 3 Lisbon dtype: object
Now we will use Series.index attribute to set the index label for the given object.
Python3
# Creating the row axis labels series.index = [ 'City 1' , 'City 2' , 'City 3' , 'City 4' ] # Print the series print (series) |
Output :
City 1 New York City 2 Chicago City 3 Toronto City 4 Lisbon dtype: object
As we can see in the output, the Series.index attribute has successfully set the index labels for the given Series object.
We can also assign duplicate or nonunique indexes in pandas.
Python3
# Creating the row axis labels series.index = [ 'City 1' , 'City 1' , 'City 3' , 'City 3' ] # Print the series print (series) |
Output:
City 1 New York City 1 Chicago City 3 Toronto City 3 Lisbon dtype: object
Find element’s index in pandas Series
Use Series.index attribute to get the index labels of the given Series object.
Python3
# importing pandas as pd import pandas as pd Date = [ '1/1/2018' , '2/1/2018' , '3/1/2018' , '4/1/2018' ] Index_name = [ 'Day 1' , 'Day 2' , 'Day 3' , 'Day 4' ] # Creating the Series sr = pd.Series(data = Date, # Series Data index = Index_name # Index ) # Print the series print (sr) |
Output :
Day 1 1/1/2018 Day 2 2/1/2018 Day 3 3/1/2018 Day 4 4/1/2018 dtype: object
Now we will use Series.index attribute to get the index label for the given object.
Python3
# print the index labels print (sr.index) |
Output :
Index(['Day 1', 'Day 2', 'Day 3', 'Day 4'], dtype='object')
As we can see in the output, the Series.index attribute has successfully returned the index labels for the given Series object.