How to access a group of elements from pandas Series using the .iloc attribute with slicing object?

PandasServer Side ProgrammingProgramming

The pandas.Series.iloc is used to access a group of elements from pandas series object by providing integer-based location index values.

The attribute .iloc is taking integer values for accessing a particular series element. Generally, the position-based index values are represented from 0 to length-1. Beyond this range only we can access the series elements otherwise it will raise an “IndexError”. But for slice indexer, it won’t rise “IndexError” for out-of-bound index value, because it allows out-of-bounds indexing.

Example 1

import pandas as pd
import numpy as np

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

print(s)

# access number of elements by using slicing object
print("Output: ")
print(s.iloc[0:4])

Explanation

In this following example, we created a pandas series object with a list of integer values and we haven’t initialized the index labels for this series object, 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:
0 1
1 2
2 3
3 4
dtype: int64

We have accessed a group of pandas.Series element from index value 0 to 4 by sending slice indexer object to the “.iloc” attribute. The accessed group of elements is returned as another series object which is displayed in the above output block.

Example 2

import pandas as pd
import numpy as np

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

print(s)

# access number of elements by using slicing object
print("Output: ")
print(s.iloc[-1:-5:-1])

Explanation

In this example, we have applied the slicing indexer with negative bound values. Let’s see the below output block to observe the results.

Output

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

Output:
9 10
8 9
7 8
6 7
dtype: int64

The negative bound values [-1:-5:-1] are applied to the iloc attribute. Then it will return a new series object with accessed reverse ordered elements.

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

Advertisements