fix indexerror single positional indexer is out of bounds error

How to Fix – IndexError: single positional indexer is out-of-bounds

In Python, an IndexError occurs when you try to access an index that is outside the valid index range of a data structure like a list, tuple, or dataframe. This error can be frustrating, especially when you are working with large datasets. In this tutorial, we will discuss how to fix the “IndexError: single positional indexer is out-of-bounds” error that occurs when you try to access an index outside the valid index range in a dataframe in Python.

fix indexerror single positional indexer is out of bounds error

Understanding the Error

Before we dive into the solution, let’s first understand the error message. The “IndexError: single positional indexer is out-of-bounds” error occurs when you try to access an index that is outside the valid index range of a dataframe. For example, if you have a dataframe with 5 rows and you try to access the 6th row, you will get this error.

Let’s reproduce this error in an example.

import pandas as pd

# create a pandas dataframe
df = pd.DataFrame({
    'Name': ['Jim', 'Dwight', 'Oscar', 'Tobi', 'Angela'],
    'Age': [26, 30, 28, 38, 31],
    'Department': ['Sales', 'Sales', 'Accounting', 'HR', 'Accounting']
})

# try to access the 6th row, row at index 5
print(df.iloc[5])

Output:

---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

Cell In[9], line 11
      4 df = pd.DataFrame({
      5     'Name': ['Jim', 'Dwight', 'Oscar', 'Tobi', 'Angela'],
      6     'Age': [26, 30, 28, 38, 31],
      7     'Department': ['Sales', 'Sales', 'Accounting', 'HR', 'Accounting']
      8 })
     10 # try to access the 6th row, row at index 5
---> 11 print(df.iloc[5])

File ~/miniforge3/envs/dsp/lib/python3.8/site-packages/pandas/core/indexing.py:931, in _LocationIndexer.__getitem__(self, key)
    928 axis = self.axis or 0
    930 maybe_callable = com.apply_if_callable(key, self.obj)
--> 931 return self._getitem_axis(maybe_callable, axis=axis)

File ~/miniforge3/envs/dsp/lib/python3.8/site-packages/pandas/core/indexing.py:1566, in _iLocIndexer._getitem_axis(self, key, axis)
   1563     raise TypeError("Cannot index by location index with a non-integer key")
   1565 # validate the location
-> 1566 self._validate_integer(key, axis)
   1568 return self.obj._ixs(key, axis=axis)

File ~/miniforge3/envs/dsp/lib/python3.8/site-packages/pandas/core/indexing.py:1500, in _iLocIndexer._validate_integer(self, key, axis)
   1498 len_axis = len(self.obj._get_axis(axis))
   1499 if key >= len_axis or key < -len_axis:
-> 1500     raise IndexError("single positional indexer is out-of-bounds")

IndexError: single positional indexer is out-of-bounds

We get the IndexError: single positional indexer is out-of-bounds error.

Fixing the error

To fix the “IndexError: single positional indexer is out-of-bounds” error, you need to make sure that you are accessing a valid index in the dataframe. Here are some ways to do that:

1) Use an index within the index range

If the index that you’re trying to use lies within the index range (that is, it’s a valid index in the dataframe), you’ll not get this error. For example, in the above dataframe, if we use the index 4, representing the row 5, we’ll not get an error.

# try to access the 5th row, row at index 4
print(df.iloc[4])

Output:

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Name              Angela
Age                   31
Department    Accounting
Name: 4, dtype: object

But we cannot always know beforehand whether an index is a valid index or not.

2) Check if the index is within the valid range using If statement

One way to avoid this error is to use conditional statements to check if the index is within the valid range before accessing it. Here’s an example:

# try to access the 6th row, row at index 5
index = 5
if index < len(df):
    print(df.iloc[index])
else:
    print("Index out of range")

Output:

Index out of range

In the above example, we first check if the row index we’re trying to access is less than the dataframe’s length. If it is, we access the row at the given index using the iloc function. If it’s not, we print a message saying that the index is out of range.

3) Using try-except

Alternatively, you can also use exception handling to handle this error.

# try to access the 6th row, row at index 5
try:
    index = 5
    print(df.iloc[index])
except IndexError:
    print("Index out of range")

Output:

Index out of range

Conclusion

The “IndexError: single positional indexer is out-of-bounds” error occurs when you try to access an index outside the valid index range in a dataframe in Python. To fix the error, you need to make sure that you are accessing a valid index in the dataframe. You can check the index range, use conditional statements, or error handling to avoid this error.

You might also be interested in –

Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top