IndexError Single Positional Indexer is Out-of-bounds Error

IndexError: single positional indexer is out-of-bounds occurs when you tried to access or call or maybe use any memory that is beyond the scope of the index. It is a special type of error that most occur in Python when dealing with index. A simple example to understand the error is that this error occurs when we try to access the element from the list or data frame that does not even exist. For example, if we have a list of five elements and we are using the index of the 7th element then we will get the error because there is no element at the index 7.

In this short article, we will learn how we can solve Indexerror: single positional indexer is out-of-bounds error. Moreover, we will also discuss how we can understand errors in Python so that in the future we can solve such errors easily. If you have any questions, or still facing the issue, please let us know through comments, and we will try our best to help you.

IndexError: single positional indexer is out-of-bounds

How to Solve IndexError: Single Positional Indexer is out-of-bounds

The error, Indexerror: single positional indexer is out-of-bounds can be caused by many factors. It usually occurs when you tried to access or call or use memory beyond the scope of the index. Let us understand the error by taking an example. Let us assume that we have a list that contains 10 elements. The indexing starts from 0 up to 9. Now, if we used the 15th index to access the elements, which is out of the range, we will get an error.

Let us take the example in Python with a sample data frame:

# importing pandas
import pandas as pd

# creating data frame
df = pd.DataFrame({'Name':["Bashir", "Alam", "Erlan", "Mirzo"],
                  "CGPA": [2.5, 3.4, 3.6, 3.8], 
                  "Major": ["CS", 'CS', "CS", "Cs"]})

# printing dataset
print(df)

# accessing elements
item = df.iloc[0, 1]

Output:

     Name  CGPA Major
0  Bashir   2.5    CS
1    Alam   3.4    CS
2   Erlan   3.6    CS
3   Mirzo   3.8    Cs
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/tmp/ipykernel_57159/413889589.py in <module>
     11 
     12 # accessing elements
---> 13 item = df.iloc[0, 10]

~/.local/lib/python3.10/site-packages/pandas/core/indexing.py in __getitem__(self, key)
   1065             key = tuple(com.apply_if_callable(x, self.obj) for x in key)
   1066             if self._is_scalar_access(key):
-> 1067                 return self.obj._get_value(*key, takeable=self._takeable)
   1068             return self._getitem_tuple(key)
   1069         else:

~/.local/lib/python3.10/site-packages/pandas/core/frame.py in _get_value(self, index, col, takeable)
   3910         """
   3911         if takeable:
-> 3912             series = self._ixs(col, axis=1)
   3913             return series._values[index]
   3914 

~/.local/lib/python3.10/site-packages/pandas/core/frame.py in _ixs(self, i, axis)
   3724         # icol
   3725         else:
-> 3726             label = self.columns[i]
   3727 
   3728             col_mgr = self._mgr.iget(i)

~/.local/lib/python3.10/site-packages/pandas/core/indexes/base.py in __getitem__(self, key)
   5356             # GH#44051 exclude bool, which would return a 2d ndarray
   5357             key = com.cast_scalar_indexer(key, warn_float=True)
-> 5358             return getitem(key)
   5359 
   5360         if isinstance(key, slice):

IndexError: single positional indexer is out-of-bounds

Note that we got the error. Now, let us jump into solutions and see how we can solve such errors:

Solution-1: Use len() Function

If you are facing IndexError: single positional indexer is out-of-bounds then most probably, the reason is that you are accessing elements that are out of range. You can use the len() method to find the size of the data frame and then use the indexing accordingly. Notice that the indexing starts from 0, which means the nth element can be accessed by index value n-1.

# using len() method
x = len(df)

# print
print(x)

Output:

4

As you can see, we got 4 which is the length of the array. You can use the len() method to get the size of the data frame and then just the indexing accordingly.

Solution-2: Using Try-except Block

In Python, the try-except blocks are used to handle any kind of error. We can use the try-except block to handle the IndexError: single positional indexer is out-of-bounds error. Let us see how we can use it:

# creating data frame
df = pd.DataFrame({'Name':["Bashir", "Alam", "Erlan", "Mirzo"],
                  "CGPA": [2.5, 3.4, 3.6, 3.8], 
                  "Major": ["CS", 'CS', "CS", "Cs"]})

# using try block
try:
    x = df.iloc[0, 8]

# except block
except:
    print("There is an error in the try-block. Most probably the index is out of range")

Output:

There is an error in the try-block. Most probably the index is out of range

As you can see, we got a message that says there is an error in the indexing without crashing the script.

Solution-3: Using If-else Statements

Another way to handle the IndexError: single positional indexer is out-of-bounds error is to use if-else statements. We can use the if statement to check if the index is within the range of the data frame or not and then use the else statement to print a message if the index is out of range.

# creating data frame
df = pd.DataFrame({'Name':["Bashir", "Alam", "Erlan", "Mirzo"],
                  "CGPA": [2.5, 3.4, 3.6, 3.8], 
                  "Major": ["CS", 'CS', "CS", "Cs"]})
# index
ind = 10

# if statement
if len(df)>ind:
    x = df.iloc[0, ind]

else:
    print("There is an error in the try-block. Most probably the index is out of range")

Output:

There is an error in the try-block. Most probably the index is out of range

Note that we got a message as defined without crashing the script.

Understanding IndexError: Single Positional Indexer is out-of-bounds Error

In Python usually, the errors had two main parts. The first part of the error represents the category of the error which in this case is IndexError which means that there is something wrong with the indexing. The second part of the error gives more information specific information about the error which in this case says that a single positional indexer is out-of-bond which clearly says that the index is out or bound. Which simply means we are using an index value that is greater than the length of the list, array, or data frame.

What is IndexError in Python?

In Python, the IndexError is a type of error that mostly occurs when we try to access the element of the array, list, or data frame that is not in the range. In other words when the index value is greater than the length of the data frame.

For example, if we have a list of 3 elements and we want to access the 5th element, then we will get an IndexError because there is no element at index 5.

What is a try-except block in Python?

The try-except block in Python is used to handle errors. The code will first, check the try block and if the error occurs, then the try block will not be executed, and then except block will be executed.

Summary

In this short article, we discussed how we can solve IndexError: single positional indexer is out-of-bounds error. We discussed the main reason for causing IndexError: single positional indexer is out-of-bounds error and learned 3 different methods to handle the error. Moreover, we also covered how we can understand errors in Python.

Related Issues

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top