Online Python tutoring
Home

Pandas iloc[] Tutorial: Select Rows and Columns by Position

iloc[] in Pandas is an integer-position-based indexer. It lets you select rows and columns by their location in a DataFrame: first row, second row, third column, and so on. You can use it to retrieve a single value, select a range of rows, build a smaller DataFrame, inspect the first or last records, and update values in selected positions.

This guide moves from basic indexing to slices, negative positions, selecting rows and columns together, conditional selection, assignment, and practical data-analysis patterns. You should be familiar with a Pandas DataFrame. For label-based selection, see the Pandas loc[] tutorial.

Learn Pandas with Practical Guidance

If you need help with Python, Pandas, data analysis coursework or a project, one-to-one tutoring can help you practise these techniques with real datasets.

Get 1-on-1 Python Tutoring

1. What Is iloc[] in Pandas?

iloc[] stands for integer-location based selection. Instead of asking for a row by its index label, you ask for the row at a particular integer position. Python positions begin at zero, so position 0 is the first row, position 1 is the second row, and position 2 is the third row.

PositionMeaning
0First row or column
1Second row or column
2Third row or column
-1Last row or column
-2Second-to-last row or column
Key idea: iloc[] uses integer positions, not index labels or column names. If your DataFrame has an index labelled 100, df.iloc[0] still means its first row.

2. Create a Sample DataFrame

We will use the same student dataset in the examples. The DataFrame has six rows and seven columns, making it easy to see how row and column positions work.

Python
import pandas as pd

students = pd.DataFrame({
    "StudentID": ["S101", "S102", "S103", "S104", "S105", "S106"],
    "Name": ["Amina", "Bilal", "Sara", "Hamza", "Noor", "Usman"],
    "Department": ["Computing", "Business", "Computing", "Business", "Computing", "Business"],
    "Age": [20, 22, 21, 23, 20, 24],
    "Marks": [88, 67, 94, 72, 81, 59],
    "Attendance": [92, 78, 96, 83, 89, 65],
    "FeePaid": [True, False, True, True, False, False]
})

print(students)

Output

  StudentID   Name Department  Age  Marks  Attendance  FeePaid
0      S101  Amina  Computing   20     88          92     True
1      S102  Bilal   Business   22     67          78    False
2      S103   Sara  Computing   21     94          96     True
3      S104  Hamza   Business   23     72          83     True
4      S105   Noor  Computing   20     81          89    False
5      S106  Usman   Business   24     59          65    False

For this DataFrame, the first row is at position 0 and the last row is at position 5. Column positions are also zero-based: StudentID is column 0, Name is column 1, Department is column 2, and Marks is column 4.

3. Understand the iloc[] Syntax

The general syntax is:

Python
df.iloc[row_position, column_position]

The expression before the comma selects rows; the expression after the comma selects columns. Both parts use integer positions, slices, lists of integers, or suitable Boolean arrays.

ExpressionMeaning
df.iloc[0]First row
df.iloc[0, 1]Value in the first row and second column
df.iloc[:, 1]Second column, all rows
df.iloc[0:3, :]First three rows, all columns
df.iloc[:, 1:4]Columns at positions 1, 2 and 3
df.iloc[[0, 2, 5], [1, 4]]Rows 0, 2, 5 and columns 1, 4

A colon by itself means all positions in that direction. Therefore, df.iloc[:, 1] means every row and the column at position 1.

4. Select Rows by Position

Example 1: Select the first row

Python
print(students.iloc[0])

This returns Amina's record as a Series. The row is selected because it is at position 0, not because its index label happens to be 0.

Example 2: Select the third row

Python
print(students.iloc[2])

The third row is Sara's record. Remember that the third row has position 2 because counting starts at zero.

Example 3: Select the last row

Python
print(students.iloc[-1])

Negative positions count backwards from the end. Position -1 selects the last row, which is Usman's record in this dataset.

Example 4: Select a row range

Python
students.iloc[1:4]

This selects positions 1, 2 and 3: Bilal, Sara and Hamza. The stop position 4 is excluded. This is the standard Python slicing rule.

5. Select a Single Cell

Use two integer positions to select a particular cell. The first integer is the row position and the second is the column position.

Example 1: Name in the first row

Python
print(students.iloc[0, 1])  # Amina

Row position 0 is the first row; column position 1 is the second column, Name.

Example 2: Marks in the third row

Python
print(students.iloc[2, 4])  # 94

The value is 94 because row position 2 belongs to Sara and column position 4 is Marks.

Example 3: Select a cell from the last row and last column

Python
print(students.iloc[-1, -1])  # False

Both row and column positions can be negative. Here, the expression returns the final value in the DataFrame: Usman's FeePaid value.

6. Select Columns by Position

Use a colon for all rows and an integer position for a particular column.

Example 1: Select the second column

Python
students.iloc[:, 1]

This returns the Name column as a Series. The column is selected by its position, even if you later rename it.

Example 2: Select the fifth column

Python
students.iloc[:, 4]

This returns the Marks column because it is at position 4.

Example 3: Select a range of columns

Python
students.iloc[:, 1:4]

This returns the columns at positions 1, 2 and 3: Name, Department and Age. Column position 4 is excluded.

Example 4: Select the last two columns

Python
students.iloc[:, -2:]

The slice -2: starts at the second-to-last column and continues to the end, returning Attendance and FeePaid.

7. Use Positional Slices Correctly

Slicing is one of the most common ways to use iloc[]. The start position is included, while the stop position is excluded. If the start is omitted, slicing begins at the first position. If the stop is omitted, slicing continues to the end.

ExpressionSelected positionsExplanation
df.iloc[0:3]0, 1, 2First three rows
df.iloc[:3]0, 1, 2Same as above
df.iloc[3:]3 to lastFrom the fourth row onwards
df.iloc[::2]0, 2, 4, ...Every second row, starting at 0
df.iloc[::-1]Reverse orderRows from last to first

Example 1: First three students

Python
students.iloc[:3]

Example 2: Skip the first two students

Python
students.iloc[2:]

Example 3: Every second row

Python
students.iloc[::2]

This selects positions 0, 2 and 4. A slice step of 2 means move forward by two positions each time.

Example 4: Reverse the row order

Python
students.iloc[::-1]

Reversing the display order does not permanently sort or modify the original DataFrame. It creates a selected result in reverse order.

Slice rows and columns together

Python
students.iloc[1:5, 1:5]

This selects row positions 1, 2, 3 and 4 and column positions 1, 2, 3 and 4. The output includes the Name, Department, Age and Marks columns for four students.

8. Select Specific Rows and Columns

Use a list of integer positions when the rows or columns you need are not consecutive.

Example 1: Select rows 0, 2 and 5

Python
students.iloc[[0, 2, 5]]

The result contains Amina, Sara and Usman. The list specifies row positions, not index labels.

Example 2: Select columns 1 and 4

Python
students.iloc[:, [1, 4]]

This returns the Name and Marks columns for all students.

Example 3: Select particular rows and columns together

Python
students.iloc[[0, 2, 5], [1, 4]]

This compact expression returns the names and marks for students at row positions 0, 2 and 5.

Example 4: Reorder selected columns

Python
students.iloc[:, [4, 1, 0]]

The output columns appear in the order requested: Marks, Name, StudentID. Positional selection can therefore be used to change the order of columns in a selected result.

Important: Lists passed to iloc[] must contain valid integer positions. Do not pass column names such as "Name" to iloc[]; use loc[] or ordinary column selection for names.

9. Use Negative Positions

Negative indexing is useful when you want the final rows or columns without first calculating the DataFrame's length.

Example 1: Last three rows

Python
students.iloc[-3:]

Example 2: Last column

Python
students.iloc[:, -1]

This returns the final column, FeePaid.

Example 3: Last three rows and last two columns

Python
students.iloc[-3:, -2:]

This is useful when you know that the fields of interest are at the end of a dataset, even if you do not know the total number of records.

10. Understand Series vs DataFrame Results

One integer selector usually reduces a dimension. Selecting one row often returns a Series; selecting one cell returns a scalar; selecting a list or slice of rows returns a DataFrame.

CodeTypical resultWhy
students.iloc[0]SeriesOne row selected
students.iloc[[0]]DataFrameA list of row positions is used
students.iloc[:, 1]SeriesOne column selected
students.iloc[:, [1]]DataFrameA list of column positions is used
students.iloc[0, 1]ScalarOne cell selected
students.iloc[0:1, 1:2]DataFrameSlices preserve both dimensions

To check the result type, use type(). To check its shape, use .shape on a Series or DataFrame.

Python
print(type(students.iloc[0]))
print(type(students.iloc[[0]]))
print(students.iloc[0:1, 1:2].shape)

11. Combine Conditions with iloc[]

iloc[] is designed for positional selection, while conditions are usually written using column names. A common approach is to create a Boolean mask from a condition and then pass the mask's values to iloc[]. In everyday Pandas code, loc[] is often simpler for condition-based filtering, but it is useful to understand both approaches.

Example 1: Find the positions of students scoring at least 80

Python
mask = students["Marks"] >= 80
positions = range(len(students))
selected_positions = [i for i, keep in zip(positions, mask) if keep]
print(selected_positions)
print(students.iloc[selected_positions])

The list comprehension identifies the integer positions where the condition is true. Those positions are then passed to iloc[].

Example 2: Use a NumPy Boolean array

Python
mask = (students["Marks"] >= 80).to_numpy()
print(students.iloc[mask])

A Boolean array of the same length as the number of rows can be used as the row selector. The mask must match the axis length being selected.

When should you use loc[] instead?

Python
students.loc[students["Marks"] >= 80, ["Name", "Marks"]]

This is generally clearer when the task is naturally expressed as a condition on named columns. Use iloc[] when the selection is fundamentally about positions or when you already have a positional mask or list.

12. Update Values Using iloc[]

You can assign a new value to a cell, row, column or rectangular section using iloc[]. Because positions can change after sorting, filtering or inserting columns, make sure the positions still refer to the data you intend to change.

Example 1: Update one cell

Python
updated = students.copy()
updated.iloc[0, 4] = 90
print(updated.iloc[0, [1, 4]])

The Marks value for the first row is changed from 88 to 90 in the copied DataFrame. Using .copy() keeps the original students DataFrame unchanged.

Example 2: Update a range of cells

Python
updated = students.copy()
updated.iloc[0:2, 4] = [91, 70]
print(updated.iloc[0:2, [1, 4]])

The first two rows in the Marks column receive the values 91 and 70. The number of values assigned must be compatible with the selected shape.

Example 3: Replace a complete column by position

Python
updated = students.copy()
updated.iloc[:, 3] = updated.iloc[:, 3] + 1
print(updated[["Name", "Age"]])

This increases every value in the fourth column, Age, by one. It is safer and more readable to use a column name when the operation is based on a named variable: updated["Age"] = updated["Age"] + 1.

13. Practical and Advanced Patterns

Pattern 1: Preview the first five rows

Python
df.iloc[:5]

This is a positional alternative to df.head(). For a quick preview, head() is more expressive, but iloc[] is helpful when building a larger positional selection.

Pattern 2: Select a sample section from a large dataset

Python
df.iloc[100:110, :5]

This selects rows at positions 100 through 109 and the first five columns. It is useful for inspecting a small section of a large CSV or Excel dataset.

Pattern 3: Select the final observation

Python
last_record = df.iloc[-1]

This selects the last row currently stored in the DataFrame. It does not necessarily mean the newest observation in time unless the data has already been sorted appropriately.

Pattern 4: Separate features and target by position

Python
X = df.iloc[:, :-1]
y = df.iloc[:, -1]

In a machine-learning dataset where the target column is deliberately placed last, this selects all earlier columns as features (X) and the final column as the target (y). Verify the column order before using this approach; a mistaken order can silently select the wrong target.

Pattern 5: Use iloc[] after resetting the index

Python
small = students[students["Marks"] >= 80]
print(small.iloc[0])

Filtering may leave gaps in the index labels, but iloc[0] still selects the first row of the filtered result. Its index label may be 0, 2 or another value; positional selection is independent of that label.

Pattern 6: Select alternating columns

Python
df.iloc[:, ::2]

The step of two selects columns at positions 0, 2, 4 and so on. This is useful for exploratory inspection, but avoid relying on column positions in production code if the dataset's column order can change.

Business example: Inspecting sales records

Suppose a sales dataset has columns in this order: OrderID, Region, Product, Units, Revenue, and Cost. You want to inspect rows 20 to 29 and the Product, Units and Revenue fields, which are at positions 2, 3 and 4.

Python
sales_preview = sales.iloc[20:30, [2, 3, 4]]
print(sales_preview)

This is efficient when the column positions are known and stable. If the dataset comes from multiple sources or columns may be reordered, selecting by column names with loc[] or ordinary bracket notation is usually more robust.

14. Pandas iloc[] vs loc[]

The main difference is the basis for selection: iloc[] uses integer positions, while loc[] uses index and column labels. Their slice endpoints also differ.

Featureiloc[]loc[]
Selection basisInteger positionsLabels
Row exampledf.iloc[0]df.loc[0]
Column exampledf.iloc[:, 1]df.loc[:, "Name"]
Slice stopExcludedIncluded when the label exists
Negative positionsSupportedNegative numbers are interpreted as labels, not “from the end” positions
Column namesNot used as column selectorsUsed directly as labels
Best suited forPosition-based extractionLabel-based and condition-based selection

Important example: index labels are not positions

Python
custom = students.set_index("StudentID")
print(custom.iloc[0])
print(custom.loc["S101"])

Both expressions select Amina's row here, but they do so differently. iloc[0] means the first row by position; loc["S101"] means the row whose index label is S101. If the order changes, these expressions may select different records.

Read the companion guide: Pandas loc[]: label-based selection.

15. Common iloc[] Errors and How to Fix Them

Error 1: Using a column name with iloc[]

Python
students.iloc[:, "Name"]  # Incorrect

Why it fails: iloc[] expects an integer position for this selector, not a string column label.

Fix: use students.loc[:, "Name"] or students["Name"], or use students.iloc[:, 1] if you deliberately want the second column by position.

Error 2: Forgetting zero-based indexing

students.iloc[1] selects the second row, not the first. Use students.iloc[0] for the first row.

Error 3: Expecting the stop position to be included

students.iloc[1:4] selects positions 1, 2 and 3. It does not include position 4. The same rule applies to column slices.

Error 4: Selecting a position outside the valid range

Python
students.iloc[6]  # IndexError: position is out of bounds

There are six rows, so the valid non-negative row positions are 0 through 5. To inspect the dimensions and column order, use:

Python
print(students.shape)
print(len(students.columns))
print(students.columns.tolist())

Error 5: Assuming index labels are positions

After setting an index to student IDs or dates, the labels may no longer be consecutive integers. iloc[0] still means the first row; it does not mean “index label 0”.

Error 6: Selecting the wrong column after a schema change

If another column is inserted before Marks, iloc[:, 4] may no longer refer to Marks. Use named columns when the meaning of a field matters more than its current position.

Error 7: Mismatched assignment sizes

When assigning a list or array to a selected region, its length and shape must fit the selected cells. If two rows are selected in one column, provide two compatible values or assign a single scalar that can be broadcast.

16. Practice Exercises with Solutions

Try each task before opening its solution. All exercises use the students DataFrame created earlier.

Exercise 1: Select the first row.

Solution:

Python
students.iloc[0]
Exercise 2: Select the Marks value for the third student.

Solution:

Python
students.iloc[2, 4]

The result is 94.

Exercise 3: Select the first four rows and the Name and Marks columns.

Solution:

Python
students.iloc[:4, [1, 4]]
Exercise 4: Select the last two students.

Solution:

Python
students.iloc[-2:]
Exercise 5: Select every second row.

Solution:

Python
students.iloc[::2]

This selects positions 0, 2 and 4.

Exercise 6: Select all rows and the last two columns.

Solution:

Python
students.iloc[:, -2:]
Exercise 7: Select row positions 1, 3 and 5, but only the Name and Attendance columns.

Solution:

Python
students.iloc[[1, 3, 5], [1, 5]]
Exercise 8: Make a copy and change the first student's marks to 95.

Solution:

Python
updated = students.copy()
updated.iloc[0, 4] = 95

17. Frequently Asked Questions

What does iloc mean in Pandas?

iloc means integer-location based indexing. It selects rows and columns according to their integer positions, starting at zero.

Does iloc[] use index labels?

No. It uses positions. Use loc[] when you want to select using index labels or column labels.

Is iloc[] zero-based?

Yes. Position 0 is the first row or column, position 1 is the second, and so on.

Is the stop value included in an iloc slice?

No. For example, df.iloc[0:3] selects positions 0, 1 and 2, not position 3.

Can I use negative numbers with iloc[]?

Yes. -1 selects the last position, -2 the second-to-last, and so on.

Can iloc[] select multiple rows and columns?

Yes. Use lists or slices, such as df.iloc[[0, 2], [1, 3]].

Why does iloc[] return a Series sometimes and a DataFrame other times?

Selecting a single row or column with an integer generally returns a Series. A list or slice generally preserves the selected dimension as a DataFrame. For example, df.iloc[0] is a Series, while df.iloc[[0]] is a one-row DataFrame.

Should I use iloc[] or loc[]?

Use iloc[] when positions are what matter. Use loc[] when you know row or column labels, or when filtering by conditions on named columns is clearer.

Continue Learning Pandas

Summary: Use iloc[] when you need to select data by integer position. Remember that positions start at zero, slice stop values are excluded, negative positions count from the end, and column order matters. When the meaning of a row or column is identified by a label rather than its position, prefer loc[].



Stuck Learning Python?

Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.

Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.

    Get Python Tutoring

PythonTutor.net

Home    Tutorial     Online Live Trainings    Contact Us           © 2026 All rights reserved by www.PythonTutor.net