Indexerror: iloc cannot enlarge its target object

IndexError: iloc cannot enlarge its target object

The error “IndexError: iloc cannot enlarge its target object” occurs when you try to assign a value to a new index that is out of bounds in pandas DataFrame using the iloc indexer.

The iloc indexer in pandas is used to access or modify the values of a DataFrame based on its integer position. It allows you to select rows and columns by their integer index rather than by label. However, the iloc indexer has a limitation that it cannot automatically enlarge the DataFrame if you try to assign a value to an index that is outside the current range.

Example

Let’s consider an example where we have a DataFrame with 3 rows and 2 columns:

import pandas as pd

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

print(df)
   col1  col2
0     1     4
1     2     5
2     3     6

If we try to assign a value to an index that is greater than the current range, we will encounter the IndexError: iloc cannot enlarge its target object error:

# Trying to assign a value to index 3 which is out of bounds
df.iloc[3] = [7, 8]

This will result in the following error:

IndexError: iloc cannot enlarge its target object

To resolve this error, you need to ensure that you are assigning values within the current range of the DataFrame. If you want to add a new row, you can use the append() method instead. Here’s an example:

# Appending a new row to the DataFrame
df = df.append(pd.Series([7, 8], index=df.columns), ignore_index=True)

print(df)
   col1  col2
0     1     4
1     2     5
2     3     6
3     7     8

In this example, we used the append() method to add a new row with values [7, 8] to the DataFrame. The ignore_index=True parameter ensures that the index is automatically generated, and the resulting DataFrame now has 4 rows.

Read more

Leave a comment