Explain the different ways in which data from a series data structure can be accessed in Python?

PythonServer Side ProgrammingProgramming

The ability to index elements and access them using their positional index values serves a great purpose when we need to access specific values.

Let us see how series data structure can be index to get value from a specific index.

Example

Live Demo

import pandas as pd
my_data = [34, 56, 78, 90, 123, 45]
my_index = ['ab', 'mn' ,'gh','kl', 'wq', 'az']
my_series = pd.Series(my_data, index = my_index)
print("The series contains following elements")
print(my_series)
print("The second element (zero-based indexing)")
print(my_series[2])
print("Elements from 2 to the last element are")
print(my_series[2:])

Output

The series contains following elements
ab  34
mn  56
gh  78
kl  90
wq  123
az  45
dtype: int64
The second element (zero-based indexing)
78
Elements from 2 to the last element are
gh  78
kl  90
wq  123
az  45
dtype: int64

Explanation

• The required libraries are imported, and given alias names for ease of use.

• A list of data values is created, that is later passed as a parameter to the ‘Series’ function present in the ‘pandas’ library

• Next, customized index values are stored in a list.

• A specific index element is accessed from the series using indexing ability of Python.

• Python also contains indexing ability, where the operator ‘:’ can be used to specify a range of elements that need to be accessed/displayed.

• It is then printed on the console.

Updated on 10-Dec-2020 13:39:25