Pandas Series Index() Methods
Last Updated :
23 Feb, 2023
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
import pandas as pd
series = pd.Series([ 'New York' , 'Chicago' , 'Toronto' , 'Lisbon' ])
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
series.index = [ 'City 1' , 'City 2' , 'City 3' , 'City 4' ]
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
series.index = [ 'City 1' , 'City 1' , 'City 3' , 'City 3' ]
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
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' ]
sr = pd.Series(data = Date,
index = Index_name
)
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.
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.
Share your thoughts in the comments
Please Login to comment...