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

Pandas df.loc() function

Pandas df.loc() function

Pandas Common Functions Common Pandas functions


loc[] is a label-based indexing method in Pandas, used to select data by row and column labels. It is one of the most intuitive and commonly used methods for DataFrame indexing, able to precisely locate the data we need.

Compared with position-based indexing (such as iloc[]),loc[] uses the index labels set on the data itself. This means that even if the position of the data changes, as long as the labels remain unchanged, we can still accurately select the target data.


Basic syntax and parameters

loc[] is an indexer for DataFrame, accessed via square brackets [] to access it. Various forms of arguments can be passed inside the brackets to select rows, columns, or specific cells.

Syntax format



# Select a single row (returns Series)

DataFrame.loc[行标签]



# Select multiple rows (return DataFrame)

DataFrame.loc[[行标签1, 行标签2, ...]]



# Select rows and columns

DataFrame.loc[行标签, 列标签]

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

DataFrame.loc[行条件, 列条件]

Parameter Description

Parameter position Parameter type Description
First parameter (row) label, list of labels, label slice, boolean array used to select rows; it can be a single label, multiple labels, a slice, or a conditional expression.
Second parameter (column) label, list of labels, label slice optional, used to select columns, with the same syntax as row selection.

Return value description


Example

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

Example 1: Basic usage - Using the default index

When a DataFrame uses the default integer index,loc[] behavior is the same as iloc[] similar, but uses labels rather than positions.

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 a single row using loc (by index label)

print

(

"Select row 0:"

)

print

(

df.

loc

[

0

]

)

print

(

)

Select multiple rows

print

(

"Selecting rows 1, 3, and 4:"

)

print

(

df.

loc

[

[

1

,

3

,

4

]

]

)

print

(

)

Use a slice to select consecutive rows (note: loc slices are inclusive of both ends)

print

(

"Select rows 1 to 3 (inclusive):"

)

print

(

df.

loc

[

1

:

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



Select row 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 行(包含两端):

      name  age  score grade

1      Bob   19     92     A

2  Charlie   17     78     B

3    David   18     90     A

Code analysis:

  1. By default, a DataFrame's index consists of the integers 0, 1, 2, 3, 4.
  2. df.loc[0] Select the row with index label 0, returning a Series.
  3. df.loc[[1, 3, 4]] Select rows with multiple specific indices.
  4. Important:loc[] slices are inclusive of both ends (unlike Python slices),1:3 includes indices 1, 2, 3.

Example 2: Using a custom index

loc[] Its real power lies in the ability to use custom index labels, which is the fundamental difference from iloc[] position-based indexing.

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

]

,

   

'grade'

:

[

'A'

,

'A'

,

'B'

,

'A'

,

'B'

]

}

df

=

pd.

DataFrame

(

data

,

index

=

[

'a'

,

'b'

,

'c'

,

'd'

,

'e'

]

)

print

(

"DataFrame with a custom index:"

)

print

(

df

)

print

(

)

Select a single row using a custom label

print

(

"Select the row with index 'b':"

)

print

(

df.

loc

[

'b'

]

)

print

(

)

Use a custom label slice

print

(

"Select rows with index 'b' to 'd':"

)

print

(

df.

loc

[

'b'

:

'd'

]

)

print

(

)

Select multiple non-consecutive indices

print

(

"Select rows with indices 'a', 'c', 'e':"

)

print

(

df.

loc

[

[

'a'

,

'c'

,

'e'

]

]

)

Running result:



带自定义索引的 DataFrame:

   name  age  score grade

a  Alice   18     85     A

b    Bob   19     92     A

c  Charlie   17     78     B

d  David   18     90     A

e    Eve   20     88     B



Select the row with index 'b':

name        Bob

age          19

score        92

grade         A

Name: b, dtype: object



Select rows with indices 'b' to 'd':

      name  age  score grade

b    Bob   19     92     A

c  Charlie   17     78     B

d  David   18     90     A



Select rows with indices 'a', 'c', 'e':

      name  age  score grade

a  Alice   18     85     A

c  Charlie   17     78     B

e    Eve   20     88     B

Code analysis:

Example 3: Selecting specific columns

loc[] You can select not only rows but also columns at the same time.

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

,

index

=

[

'a'

,

'b'

,

'c'

,

'd'

,

'e'

]

)

Select specific columns of a specific row

print

(

"Select the name and score columns for index 'b':"

)

print

(

df.

loc

[

'b'

,

[

'name'

,

'score'

]

]

)

print

(

)

Select multiple rows and multiple columns

print

(

"Select the name and age columns for indices 'a', 'c':"

)

print

(

df.

loc

[

[

'a'

,

'c'

]

,

[

'name'

,

'age'

]

]

)

print

(

)

Select specific columns of all rows

print

(

"Select the name and grade columns for all rows:"

)

print

(

df.

loc

[

:

,

[

'name'

,

'grade'

]

]

)

print

(

)

Combining a row slice and a column slice

print

(

"Select the name to score columns for indices 'b' to 'd':"

)

print

(

df.

loc

[

'b'

:

'd'

,

'name'

:

'score'

]

)

Running result:



Select the name and score columns of index 'b':

name     Bob

score    92

Name: b, dtype: object



Select the name and age columns of indices 'a' and 'c':

    name  age

a  Alice   18

c  Charlie 17



The name and grade columns of all rows:

    name grade

a   Alice     A

b     Bob     A

c  Charlie   B

d    David    A

e     Eve      B



Columns from name to score for indices 'b' to 'd':

      name  age score

b    Bob   19    92

c  Charlie 17    78

d  David   18    90

Code analysis:

  1. df.loc['b', ['name', 'score']] Select specific columns of a specific row, returning a Series.
  2. df.loc[['a', 'c'], ['name', 'age']] Select multiple rows and columns, returning a DataFrame.
  3. df.loc[:, ['name', 'grade']] A colon means selecting all rows.
  4. df.loc['b':'d', 'name':'score'] Use slices for both rows and columns at the same time.

Example 4: Selecting with boolean conditions

loc[] supports using boolean arrays or conditional expressions to filter data, which is a very powerful feature.

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

)

Use a boolean condition to select rows with scores greater than 85

print

(

"Students with scores greater than 85:"

)

print

(

df.

loc

[

df

[

'score'

]

>

;

85

]

)

print

(

)

Compound condition: score greater than 85 and age less than 19

print

(

"Students with scores greater than 85 and age less than 19:"

)

print

(

df.

loc

[

(

df

[

'score'

]

>

;

85

)

&

;

(

df

[

'age'

]

 

85

,

[

'name'

,

'score'

]

]

)

Running result:



Students with scores greater than 85:

      name  age  score grade

1      Bob   19     92     A

3    David   18     90     A

4      Eve   20     88     B



Students with a score greater than 85 and age less than 19:

      name  age  score grade

3    David   18     90     A



Rows selected using a boolean array:

      name  age  score grade

0    Alice   18     85     A

2  Charlie   17     78     B

4      Eve   20     88     B



分数大于 85 的学生的 name 和 score:

      name  score

1      Bob     92

3    David   90

4      Eve    88

Code analysis:

  1. df.loc[df['score'] > 85] Filter using boolean conditions, returning rows that satisfy the condition.
  2. Compound conditions need to be enclosed in parentheses and joined with &(and) and |(or).
  3. You can pass a boolean array directly (its length must equal the number of rows) to select rows.
  4. A column selection can follow the condition to achieve fine-grained data filtering.

Notes

Important note:loc[] and iloc[] are two different indexers; although they look similar, their principles are completely different:loc[] Label-based,iloc[] is position-based. When using them, choose the appropriate indexer according to the actual situation.


Summary

loc[] is a label-based data selector in Pandas, providing an intuitive and flexible way to access data. Through the combination of row and column labels, we can precisely select any data we need.

Its main advantages include: using custom indexes makes code more readable, supporting inclusive slicing syntax, and enabling complex filtering with boolean conditions. In real data analysis,loc[] is one of the most frequently used indexing methods in daily work.

Pandas Common Functions Common Pandas functions