Open In App

How to Fix – Indexerror: Single Positional Indexer Is Out-Of-Bounds

Last Updated : 09 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

While working with Python, many errors occur in Python. IndexError: Single Positional Indexer is Out-Of-Bounds occurs when we are trying to access the elements and that element is not present inside the Pandas DataFrame. In this article, we will see how we can fix IndexError: single positional indexer is out-of-bounds error in Python.

What is IndexError: Single Positional Indexer Is Out-Of-Bounds Error?

The “IndexError: Single Position Indexer is Out-of-Bounds” alert displays when you the to reach an index that is not part of the sequence or array. This error is common while working with lists, tuples, arrays, and other similar types of data structures. It occurs when you attempt to access an index higher than or equal to the length of the sequence, or whenever you use a negative index that is beyond the sequence’s range.

Syntax:

 Indexerror: Single Positional Indexer Is Out-Of-Bounds

Below are the reason due to which IndexError: single positional indexer is out-of-bounds occurs in Python:

Incorrect Indexing

In this example, the below code tries to access the content at the fourth position of the data frame using iloc, resulting in an IndexError because there are only three rows in the DataFrame.

Python3
import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

print(df.iloc[3])

Output

File “C:\Users\GFG0371\Downloads\New folder\env\Lib\site-packages\pandas\core\indexing.py”, line 1685, in _validate_integer

raise IndexError(“single positional indexer is out-of-bounds”)

IndexError: single positional indexer is out-of-bounds

Solution for Indexerror: Single Positional Indexer Is Out-Of-Bounds

Below are some of the ways by which we can fix Indexerror: Single Positional Indexer Is Out-Of-Bounds in Python:

Correct Indexing

Below, code creates a DataFrame with two columns (‘A’ and ‘B’) and three rows of data, then prints the fourth row using integer-based indexing.

Python3
import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})

print(df.iloc[3:4])

Output:

Empty DataFrame
Columns: [A, B]
Index: []

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads