Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas df.iloc[] function

Pandas df.iloc[] function

Pandas Common Functions Common Pandas functions


iloc[] is an indexing method in Pandas based on integer location, used to select data by row and column numbers. It differs from loc[] in Vue 2,iloc[] in that it is entirely based on data position (zero-based integer indexing), without considering the labels set on the data itself.

When you need to select data by position, or when you don't know the specific index labels,iloc[] is the best choice. It works very similarly to Python list indexing, making it very intuitive for Python users.


Basic syntax and parameters

iloc[] is an indexer for DataFrame, accessed via square brackets [] . It accepts only integers, lists of integers, integer slices, or boolean arrays as arguments.

Syntax format



# Select a single row (returns Series)

DataFrame.iloc[行号]



# Select multiple rows (return DataFrame)

DataFrame.iloc[[行号1, 行号2, ...]]



# Use slicing to select consecutive rows

DataFrame.iloc[起始行:结束行]



# Select rows and columns

DataFrame.iloc[行号, 列号]

DataFrame.iloc[行切片, 列切片]

DataFrame.iloc[行列表, 列列表]

Parameter Description

Parameter position Parameter type Description
First parameter (row) Integer, list of integers, integer slice, boolean array Used to select rows, by position (starting from 0).
Second parameter (column) Integer, list of integers, integer slice Optional, used to select columns, also by position.

Return value description


Example

Let us fully master it through a wealth of examples iloc[] through a series of examples from simple to complex.

Example 1: Basic usage - selecting rows

iloc[] Uses position-based indexing, very similar to Python list indexing.

Example

import

pandas

as

pd

Create a sample 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

(

"Selecting the first row (position 0):"

)

print

(

df.

iloc

[

0

]

)

print

(

)

Select multiple rows

print

(

"Selecting rows 1, 3, and 4:"

)

print

(

df.

iloc

[

[

1

,

3

,

4

]

]

)

print

(

)

Use a slice to select consecutive rows (note: iloc slices are left-inclusive and right-exclusive, same as Python)

print

(

"Selecting rows 1 through 3 (positions 1, 2, 3):"

)

print

(

df.

iloc

[

1

:

4

]

)

print

(

)

Select the first 3 rows

print

(

"First 3 rows:"

)

print

(

df.

iloc

[

:

3

]

)

Running result:



原始 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



Select lines 1, 3, and 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:

  1. df.iloc[0] Select the first row (position 0), returning a Series.
  2. iloc[] slices are left-inclusive and right-exclusive, including positions 1, 2, 3 but not position 4.
  3. df.iloc[[1, 3, 4]] Select multiple rows at specific positions.
  4. 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 at the same time, locating them precisely by position numbers.

Example

import

pandas

as

pd

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

(

"Selecting the cell at position [1, 2]:"

)

print

(

df.

iloc

[

1

,

2

]

)

 

Returns 92

print

(

)

Select specific columns of a specific row

print

(

"Selecting columns 1 and 3 of row 0:"

)

print

(

df.

iloc

[

0

,

[

1

,

3

]

]

)

print

(

)

Select multiple rows and multiple columns

print

(

"Selecting columns 0 and 2 of rows 0, 2, and 4:"

)

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

(

)

Combining a row slice and a column slice

print

(

"Columns 0 through 2 (exclusive) of rows 1 through 3:"

)

print

(

df.

iloc

[

1

:

4

,

:

3

]

)

Running result:



Select cell at position [1, 2]:

92



Select column 1 and column 3 of row 0:

age      19

grade     A

Name: 0, dtype: object



Select rows 0, 2, 4 and columns 0, 2:

      name  score

0    Alice     85

2  Charlie   78

4      Eve    88



Column 0 and Column 2 of all rows:

      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:

  1. df.iloc[1, 2] Select a single cell, returning a scalar value.
  2. df.iloc[0, [1, 3]] Select multiple columns of a specific row.
  3. df.iloc[:, [0, 2]] A colon means selecting all rows.
  4. iloc[] slices follow the Python convention of being left-inclusive and right-exclusive (excluding the end position).

Example 3: Combining with a custom index

When a DataFrame has a custom index,iloc[] still selects data by position, regardless of the index labels.

Example

import

pandas

as

pd

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 a custom index:"

)

print

(

df

)

print

(

)

iloc still selects by position and is unaffected by the custom index

print

(

"iloc[0] selects the first row (position 0):"

)

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 indices (counting from the end)

print

(

"Last row (position -1):"

)

print

(

df.

iloc

[

1

]

)

print

(

)

print

(

"Last 3 rows:"

)

print

(

df.

iloc

[

3

:

]

)

Running result:



带自定义索引的 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] selects the first row (position 0), independent of labels '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



Last 3 lines:

      name  age  score

c  Charlie   17     78

d    David   18     90

e      Eve   20     88

Code analysis:

Example 4: Selecting with a boolean array

iloc[] also supports selection with a boolean array, which is useful in conditional filtering.

Example

import

pandas

as

pd

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 a condition (first compute the boolean array, then use it with iloc)

Select rows where the score is greater than 85

condition

=

df

[

'score'

]

>

;

85

print

(

"Rows where the score is greater than 85:"

)

print

(

df.

iloc

[

condition.

values

]

)

 

Get the boolean array

print

(

)

After selecting rows at specific positions, select specific columns

print

(

"Columns 1 and 2 of rows 1 and 3:"

)

print

(

df.

iloc

[

[

1

,

3

]

,

1

:

3

]

)

Running result:



Rows selected using the boolean array [True, False, True, False, True]:

      name  age  score grade

0    Alice   18     85     A

2  Charlie   17     78     B

4      Eve   20     88     B



Rows with score greater than 85:

      name  age  score grade

1      Bob   19     92     A

3    David   18     90     A

4      Eve   20     88     B



The 1st and 3rd lines, the 1st and 2nd columns:

      age  score

1     19     92

3     18     90

Code analysis:

  1. The length of the boolean array must match the number of rows (for row selection) or columns (for column selection).
  2. iloc When using a boolean array, unlike loc[] conditional filtering, it selects directly by position.
  3. You can use a slice step to select specific patterns, such as selecting every other row.

Notes

Important note:loc[] and iloc[] The difference between them is a key point in learning Pandas.loc[] Label-based,iloc[] Position-based. During development, it is recommended to clearly distinguish the two to avoid errors caused by confusion.


Summary

iloc[] is a data selector in Pandas based on integer positions, providing an indexing experience similar to Python lists. Its main feature is that it is entirely based on data position (starting from 0), unaffected by custom index labels.

In practical use,iloc[] is especially suitable for the following scenarios: selecting data by position, using negative indices, using slice steps, and selecting data when index labels are uncertain. Combined with loc[] and iloc[], it can flexibly handle various data selection needs.

Pandas Common Functions Common Pandas functions