How to access Pandas Series elements by using indexing?

PandasServer Side ProgrammingProgramming

The data present in the pandas Series object has indexing labels, those index labels are used to access or retrieve elements. Each index value addresses an element in series.

Indexes are basically represented in two types: positional indexing and labeled indexing. Positional indexing is nothing but integer values starting from 0 to n-1 (n number of elements present in series). Whereas labeled indexing is user-defined labels that can be anything like integers, objects, date times and etc.,

Example

# importing required packages
import pandas as pd
import numpy as np

# creating pandas Series object
series = pd.Series(np.random.rand(10))
print(series)

print('\nAccessing elements by using index values')
# accessing elements by using index values
print(series[[2,7]])

Explanation

The following example will create a positional indexed pandas Series object with 10 randomly generated values by using the NumPy.random model.

The series[[2,7]] will access the 2 and 7 addressed elements from our series object at a time. If you want to access one element then we can say it like this series[index_values].

Output

0   0.517225
1   0.933815
2   0.183132
3   0.333059
4   0.993192
5   0.826969
6   0.761213
7   0.274025
8   0.129120
9   0.901257
dtype: float64

Accessing elements by using index values
2   0.183132
7   0.274025
dtype: float64

0.183132 and 0.274025 are the values for the positional index of 2,7 from our series object.

Example

If we have labeled index data, and we want to access the series elements then we can specify those labeled index addresses to retrieve elements.

# importing required packages
import pandas as pd
import numpy as np

# creating pandas Series object
series = pd.Series({'black':'white', 'body':'soul', 'bread':'butter', 'first':'last'})
print(series)

print('\nAccessing elements by using index labels')
# accessing elements by using index values
print(series['black'])

Explanation

Initially, we have created a Series object with labeled index data using a python dictionary with string-type keys and values, and these keys act as our index values.

In this example, we are accessing an element with an address ‘black’ so the resultant output will be seen in the output block.

Output

black   white
body     soul
bread  butter
first    last
dtype: object

Accessing elements by using index labels
white

The output for the label ‘black’ is ‘white’, in the same way, we can access labeled elements from a series. The first block of the above output is an entire series object.

raja
Updated on 17-Nov-2021 07:45:18

Advertisements