When using the iloc
function in Pandas, there are some common mistakes that people often make. Here are a few examples along with code samples to illustrate these mistakes:
1. Misusing `iloc` with incorrect index positions:
In the below example, the code attempts to use iloc
with index position 3 to select a row. However, the valid index positions in the DataFrame are 0, 1, and 2. This will result in an IndexError
because there is no row at index position 3.
To correct this mistake, you should use the appropriate index positions based on the dataframe’s size.
2. Mixing up iloc with loc:
In the example below, the code attempts to use iloc
with row index position 0 and column label ‘Age’ to select a specific value. However, iloc
expects integer-based index positions for both rows and columns and loc
uses label-based positions.
To correct this mistake, you should use integer-based index positions for both rows and columns.
3. Using a single integer instead of a list or array-like object:
Another mistake is passing a single integer to iloc
instead of a list or array-like object. iloc
expects a sequence of integers for indexing multiple rows or columns. Here’s an example: