How to retrieve multiple elements from a series when the index is customized Python?


When the index values are customized, they are accessed using series_name[‘index_value’].

The ‘index_value’ passed to series is tried to be matched to the original series. If it is found, that corresponding data is also displayed on the console.

Let us see how multiple elements can be displayed.

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("Accessing multiple elements using customized index")
print(my_series[['mn', 'az', 'wq', 'ab']])

Output

The series contains following elements
ab  34
mn  56
gh  78
kl  90
wq  123
az  45
dtype: int64
Accessing multiple elements using customized index
mn  56
az  45
wq  123
ab  34
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 (that are passed as parameter later) are stored in a list.

  • The series is created and index list and data are passed as parameters to it.

  • The series is printed on the console.

  • Since the index values are customized, they are used to access the values in the series like series_name[‘index_name’].

  • When multiple index values need to be accessed, they are first specified in a list and then series indexing can be used to access these values.

  • Note − Observe the two ‘[[‘ in the code.

  • It is then printed on the console.

Updated on: 10-Dec-2020

801 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements