How to access pandas Series elements using the .iloc attribute?

PandasServer Side ProgrammingProgramming

The pandas.Series.iloc attribute is used to access elements from pandas series object that is based on integer location-based indexing. And It is very similar to pandas.Series “iat” attribute but the difference is, the “iloc” attribute can access a group of elements whereas the “iat” attribute access only a single element.

The “.iloc” attribute is used to allows inputs values like an integer value, a list of integer values, and a slicing object with integers, etc.

Example 1

import pandas as pd
import numpy as np

# create a pandas series
s = pd.Series([1,2,3,4,5,6,7,8,9,10])

print(s)

print("Output: ")
print(s.iloc[2])

Explanation

In this following example, we created a pandas series object “s” using a python list of integers and we haven’t initialized the index labels, so the pandas.Series constructor will provide a range of index values based on the data given to the pandas.Series constructor.

For this example, the integer location-based indexing starts from 0 to 9.

Output

0  1
1  2
2  3
3  4
4  5
5  6
6  7
7  8
8  9
9  10
dtype: int64

Output: 3

We have accessed a single element from pandas.Series object by providing the integer-based index value to the “iloc” attribute.

Example 2

import pandas as pd
import numpy as np

# create a series
s = pd.Series([1,2,3,4,5,6,7,8,9,10])

print(s)

# access number of elements by using a list of integers
print("Output: ")
print(s.iloc[[1,4,5]])

Explanation

Let’s access the group of elements from pandas.Series object by providing the list of integer values that denotes the integer-based index position of a given series.

In this example, we provided the list of integers [1,4,5] to the “iloc” attribute.

Output

0  1
1  2
2  3
3  4
4  5
5  6
6  7
7  8
8  9
9  10
dtype: int64
Output:
1  2
4  5
5  6
dtype: int64

We have successfully accessed the group of pandas.Series elements by using the “iloc” attribute. as a result, it returns another series object which is displayed in the above output block.

raja
Updated on 09-Mar-2022 05:51:11

Advertisements