What does the pandas.series.index attribute do?


A Series is a pandas data structure that is used to store the labeled data in a single dimension, the labels can be anything like text data, integer values, and time sequence. by using these labels we can access elements of a given series and we can do data manipulations too.

In pandas.Series the labels are called indexes, If you want to get index labels separately then we can use pandas.Series “index” attribute.

Example 1

import pandas as pd

# creating a series
s = pd.Series([100,110,120,130,140])
print(s)

# Getting index data
index = s.index

print('Output: ')

# displaying outputs
print(index)

Explanation

Initialized a pandas Series object using a python list with integer values of length 5. The s.index attribute will return a list of index labels based on the given series object.

Output

0  100
1  110
2  120
3  130
4  140
dtype: int64

Output:
RangeIndex(start=0, stop=5, step=1)

At the time of creating the series object, we haven’t initialized the index labels for this example. So the pandas.Series Constructor will automatically provide the index labels.

The index attribute access the auto-created label (RangeIndex values), and those are displayed in the above output block.

Example 2

import pandas as pd

Countrys = ['Iceland', 'India', 'United States']
Capitals = [ 'Reykjavik', 'New Delhi', 'Washington D.C']

# create series
s = pd.Series(Capitals, index=Countrys)

# display Series
print(s)

# Getting index data
index = s.index

print('Output: ')
# displaying outputs
print(index)

Explanation

In the following example, we have created a pandas Series using two python list-objects each list is holding country’s names (strings), and capital cities names.

Output

Iceland              Reykjavik
India                New Delhi
United States   Washington D.C
dtype: object
Output:
Index(['Iceland', 'India', 'United States'], dtype='object')

The s.index attribute will return a list of labels of the given series object “s”, and the data type of those index labels are “object” type.

Updated on: 09-Mar-2022

316 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements