Pandas df.iloc[] Function
iloc[]It is an integer-location-based indexing method in Pandas, used to select data by row and column numbers. It isloc[]different,iloc[]completely based on the position of the data (integer index starting from 0), without considering the labels set on the data itself.
When you need to select data by position, or select data without knowing the specific index labels,iloc[]it is the best choice. Its working method is very similar to Python list indexing, making it very intuitive for Python users.
Basic Syntax and Parameters
iloc[]It is the indexer of DataFrame, accessed through square brackets[]It only accepts integers, integer lists, integer slices, or boolean arrays as parameters.
Syntax Format
# 选择单行(返回 Series) DataFrame.iloc[行号] # 选择多行(返回 DataFrame) DataFrame.iloc[[行号1, 行号2, ...]] # 使用切片选择连续行 DataFrame.iloc[起始行:结束行] # 选择行和列 DataFrame.iloc[行号, 列号] DataFrame.iloc[行切片, 列切片] DataFrame.iloc[行列表, 列列表]
Parameter Description
| Parameter Position | Parameter Type | Description |
|---|---|---|
| First parameter (rows) | Integer, integer list, integer slice, boolean array | Used to select rows, based on position (starting from 0). |
| Second parameter (columns) | Integer, integer list, integer slice | Optional, used to select columns, also based on position. |
Return Value Description
- Single element: returns a scalar value.
- Single row: returns a Series.
- Multiple rows: returns a DataFrame.
- Combination of rows and columns: returns a Series or DataFrame depending on the selection result.
Examples
Let us comprehensively masteriloc[]its usage through rich examples.
Example 1: Basic Usage - Selecting Rows
iloc[]Uses position-based indexing, very similar to Python list indexing.
Example
# Create example DataFrame
data = {
'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'age': [18, 19, 17, 18, 20],
'score': [85, 92, 78, 90, 88],
'grade': ['A', 'A', 'B', 'A', 'B']
}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
print()
# Select the first row (index 0)
print("Select the first row (position 0):")
print(df.iloc[0])
print()
# Select multiple rows
print("Select rows 1, 3, 4:")
print(df.iloc[[1, 3, 4]])
print()
# Use slicing to select consecutive rows (note: iloc slicing is left-closed and right-open, same as Python)
print("Select rows 1 to 3 (positions 1, 2, 3):")
print(df.iloc[1:4])
print()
# Select the first 3 rows
print("First 3 rows:")
print(df.iloc[:3])
Output:
原始 DataFrame:
name age score grade
0 Alice 18 85 A
1 Bob 19 92 A
2 Charlie 17 78 B
3 David 18 90 A
4 Eve 20 88 B
选择第一行(位置 0):
name Alice
age 18
score 85
grade A
Name: 0, dtype: object
选择第 1、3、4 行:
name age score grade
1 Bob 19 92 A
3 David 18 90 A
4 Eve 20 88 B
选择第 1 行到第 3 行(位置 1、2、3):
name age score grade
1 Bob 19 92 A
2 Charlie 17 78 B
3 David 18 90 A
前 3 行:
name age score grade
0 Alice 18 85 A
1 Bob 19 92 A
2 Charlie 17 78 B
Code Analysis:
df.iloc[0]Selecting the first row (position 0) returns a Series.iloc[]Slicing is left-closed and right-open, including positions 1, 2, 3, but not position 4.df.iloc[[1, 3, 4]]Selects rows at multiple specific positions.df.iloc[:3]Omitting the start position means starting from 0.
Example 2: Selecting Specific Rows and Columns
iloc[]You can select rows and columns simultaneously, precisely locating them by position numbers.
Example
data = {
'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'age': [18, 19, 17, 18, 20],
'score': [85, 92, 78, 90, 88],
'grade': ['A', 'A', 'B', 'A', 'B']
}
df = pd.DataFrame(data)
# Select a single cell (second row, third column)
print("Select the cell at position [1, 2]:")
print(df.iloc[1, 2]) # returns 92
print()
# Select specific columns of a specific row
print("Select columns 1 and 3 of row 0:")
print(df.iloc[0, [1, 3]])
print()
# Select multiple rows and columns
print("Select rows 0, 2, 4 and columns 0, 2:")
print(df.iloc[[0, 2, 4], [0, 2]])
print()
# Select specific columns of all rows
print("Columns 0 and 2 of all rows:")
print(df.iloc[:, [0, 2]])
print()
# Combine row slicing and column slicing
print("Rows 1 to 3, columns 0 to 2 (exclusive):")
print(df.iloc[1:4, :3])
Output:
选择位置 [1, 2] 的单元格:
92
选择第 0 行的第 1 和第 3 列:
age 19
grade A
Name: 0, dtype: object
选择第 0、2、4 行的第 0、2 列:
name score
0 Alice 85
2 Charlie 78
4 Eve 88
所有行的第 0 和第 2 列:
name score
0 Alice 85
1 Bob 92
2 Charlie 78
3 David 90
4 Eve 88
第 1 到 3 行的第 0 到第 2 列(不含):
name age
1 Bob 19
2 Charlie 17
3 David 18
Code Analysis:
df.iloc[1, 2]Selecting a single cell returns a scalar value.df.iloc[0, [1, 3]]Selects multiple columns of a specific row.df.iloc[:, [0, 2]]A colon indicates selecting all rows.iloc[]Slicing follows Python conventions, left-closed and right-open (excluding the end position).
Example 3: Using with Custom Index
When the DataFrame has a custom index,iloc[]data is still selected by position, regardless of index labels.
Example
# Create a DataFrame with a custom index
data = {
'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'age': [18, 19, 17, 18, 20],
'score': [85, 92, 78, 90, 88]
}
df = pd.DataFrame(data, index=['a', 'b', 'c', 'd', 'e'])
print("DataFrame with custom index:")
print(df)
print()
# iloc still selects by position, unaffected by the custom index
print("iloc)
print(df.iloc[0])
print()
print("iloc[1:3] selects rows 2 and 3 (positions 1, 2):")
print(df.iloc[1:3])
print()
# Use negative indexing (counting from the end)
print("Last row (position -1):")
print(df.iloc[-1])
print()
print("Last 3 rows:")
print(df.iloc[-3:])
Output:
带自定义索引的 DataFrame:
name age score
a Alice 18 85
b Bob 19 92
c Charlie 17 78
d David 18 90
e Eve 20 88
iloc[0] 选择第一行(位置 0),与标签 'a', 'b', 'c' 无关:
name Alice
age 18
score 85
Name: a, dtype: object
iloc[1:3] 选择第 2、3 行(位置 1、2):
name age score
b Bob 19 92
c Charlie 17 78
最后一行(位置 -1):
name Eve
age 20
score 88
Name: e, dtype: object
倒数 3 行:
name age score
c Charlie 17 78
d David 18 90
e Eve 20 88
Code Analysis:
- Even if the DataFrame uses a custom index ('a', 'b', 'c', 'd', 'e'),
iloc[]it still selects by position. iloc[0]Always selects the first row (physical position), regardless of the index label.ilocSupports negative indexing: -1 represents the last row, -2 the second-to-last row, and so on.
Example 4: Selecting with Boolean Arrays
iloc[]It also supports selection using boolean arrays, which is useful for conditional filtering.
Example
data = {
'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'age': [18, 19, 17, 18, 20],
'score': [85, 92, 78, 90, 88],
'grade': ['A', 'A', 'B', 'A', 'B']
}
df = pd.DataFrame(data)
# Select using a boolean array
bool_array = [True, False, True, False, True]
print("Rows selected using the boolean array [True, False, True, False, True]:")
print(df.iloc[bool_array])
print()
# Use with conditions (first compute the boolean array, then use it with iloc)
# Select rows with scores greater than 85
condition = df['score'] > 85
print("Rows with scores greater than 85:")
print(df.iloc[condition.values]) # Get the boolean array
print()
# Select specific columns after selecting rows at specific positions
print("Rows 1 and 3, columns 1 and 2:")
print(df.iloc[[1, 3], 1:3])
Output:
使用布尔数组 [True, False, True, False, True] 选择的行:
name age score grade
0 Alice 18 85 A
2 Charlie 17 78 B
4 Eve 20 88 B
分数大于 85 的行:
name age score grade
1 Bob 19 92 A
3 David 18 90 A
4 Eve 20 88 B
第 1、3 行的第 1、2 列:
age score
1 19 92
3 18 90
Code Analysis:
- The length of the boolean array must match the number of rows (for row selection) or the number of columns (for column selection).
ilocWhen using a boolean array, unlikeloc[]conditional filtering, it directly selects by position.- You can use a slice step to select specific patterns, such as selecting every other row.
Notes
iloc[]It uses positional indexing; slicing follows Python conventions (left-closed, right-open).- If a position outside the range is passed, an IndexError is raised.
- Supports negative indexing: -1 represents the last row, -2 the second-to-last row.
- and
loc[]In contrast,iloc[]it does not support direct filtering with conditional expressions; you need to compute a boolean array first.
Important Note:
loc[]andiloc[]The difference is a key point in learning Pandas.loc[]loc is based on labels,iloc[]iloc is based on positions. In development, it is recommended to clearly distinguish the two to avoid errors caused by confusion.
Summary
iloc[]It is a data selector based on integer position in Pandas, providing an indexing experience similar to Python lists. Its main characteristic is that it is completely based on the position of the data (starting from 0) and is not affected by custom index labels.
In actual use,iloc[]it is especially suitable for the following scenarios: when you need to select data by position, when you need to use negative indexing, when you need to use slice steps, and when selecting data without certain index labels. Combined withloc[]andiloc[], it can flexibly handle various data selection needs.
Common Pandas Functions