Thursday, 17 August 2023

How to Set Multiple Values for a Series Index Label in Pandas

A Pandas series index label can point to multiple values.

For example,

primes = [2, 3, 5, 7, 11, 13, 17]
primes_index = ['A', 'B', 'C', 'D', 'A', 'B', 'A']
primes_series = pd.Series(primes, index=primes_index)

 

In the above snippet, primes_series holds below data.

A     2
B     3
C     5
D     7
A    11
B    13
A    17
dtype: int64

 

From the above snippet, you can confirm that the index label ‘A’ point to three values 2, 11 and 17.

When you access the values associated with the index label ‘A’, Pandas return a series.

associated_with_index_a = primes_series['A']

 

‘associated_with_index_a’ point to below data.

A     2
A    11
A    17
dtype: int64

 

Find the below working application.

 

index_can_hold_multiple_values.py

import pandas as pd

primes = [2, 3, 5, 7, 11, 13, 17]
primes_index = ['A', 'B', 'C', 'D', 'A', 'B', 'A']
primes_series = pd.Series(primes, index=primes_index)

print('primes_series')
print(primes_series)

associated_with_index_a = primes_series['A']
print('\nassociated_with_index_a')
print(associated_with_index_a)
print('\ntype of associated_with_index_a', type(associated_with_index_a))

associated_with_index_c = primes_series['C']
print('\nassociated_with_index_c')
print(associated_with_index_c)
print('\ntype of associated_with_index_c', type(associated_with_index_c))

 

Output

primes_series
A     2
B     3
C     5
D     7
A    11
B    13
A    17
dtype: int64

associated_with_index_a
A     2
A    11
A    17
dtype: int64

type of associated_with_index_a <class 'pandas.core.series.Series'>

associated_with_index_c
5

type of associated_with_index_c <class 'numpy.int64'>

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment