Using series ‘index’ attribute, we can get the index labels of the series.
Example 1: If you do not specify the index explicitly, then a numeric index is used by default.
even_numbers = [2, 4, 6, 8]
even_numbers_series = pd.Series(even_numbers)
‘even_numbers_series.index’ return RangeIndex(start=0, stop=4, step=1)
Example 2: Explicitly specifying the index.
primes = [2, 3, 5]
primes_index = ['first_prime', 'second_prime', 'third_prime']
primes_series = pd.Series(primes, index=primes_index)
'primes_series.index' return Index(['first_prime', 'second_prime', 'third_prime'], dtype='object')
Find the below working application.
get_series_index.py
import pandas as pd
primes = [2, 3, 5]
primes_index = ['first_prime', 'second_prime', 'third_prime']
primes_series = pd.Series(primes, index=primes_index)
print('primes_series')
print(primes_series, '\n')
print('index_labels of primes_series is ', primes_series.index)
even_numbers = [2, 4, 6, 8]
even_numbers_series = pd.Series(even_numbers)
print('\neven_numbers_series')
print(even_numbers_series, '\n')
print('index_labels of even_numbers_series is ', even_numbers_series.index)
Output
primes_series first_prime 2 second_prime 3 third_prime 5 dtype: int64 index_labels of primes_series is Index(['first_prime', 'second_prime', 'third_prime'], dtype='object') even_numbers_series 0 2 1 4 2 6 3 8 dtype: int64 index_labels of even_numbers_series is RangeIndex(start=0, stop=4, step=1)
No comments:
Post a Comment