Pandas df.loc() function
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
- Single element: returns a scalar value (a single value).
- Single row: Returns a Series.
- Multiple rows: Returns a DataFrame.
- Row and column combination: Returns a Series or DataFrame depending on the selection.
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
)
(
"Original DataFrame:"
)
(
df
)
(
)
Select a single row using loc (by index label)
(
"Select row 0:"
)
(
df.
loc
[
0
]
)
(
)
Select multiple rows
(
"Selecting rows 1, 3, and 4:"
)
(
df.
loc
[
[
1
,
3
,
4
]
]
)
(
)
Use a slice to select consecutive rows (note: loc slices are inclusive of both ends)
(
"Select rows 1 to 3 (inclusive):"
)
(
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:
- By default, a DataFrame's index consists of the integers 0, 1, 2, 3, 4.
df.loc[0]Select the row with index label 0, returning a Series.df.loc[[1, 3, 4]]Select rows with multiple specific indices.- Important:
loc[]slices are inclusive of both ends (unlike Python slices),1:3includes 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'
]
)
(
"DataFrame with a custom index:"
)
(
df
)
(
)
Select a single row using a custom label
(
"Select the row with index 'b':"
)
(
df.
loc
[
'b'
]
)
(
)
Use a custom label slice
(
"Select rows with index 'b' to 'd':"
)
(
df.
loc
[
'b'
:
'd'
]
)
(
)
Select multiple non-consecutive indices
(
"Select rows with indices 'a', 'c', 'e':"
)
(
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:
- A custom index uses the strings 'a', 'b', 'c', 'd', 'e' instead of integer indices.
loc[]Using these labels to select data is very intuitive.- The slice 'b':'d' includes labels 'b', 'c', 'd', and is likewise inclusive of both ends.
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
(
"Select the name and score columns for index 'b':"
)
(
df.
loc
[
'b'
,
[
'name'
,
'score'
]
]
)
(
)
Select multiple rows and multiple columns
(
"Select the name and age columns for indices 'a', 'c':"
)
(
df.
loc
[
[
'a'
,
'c'
]
,
[
'name'
,
'age'
]
]
)
(
)
Select specific columns of all rows
(
"Select the name and grade columns for all rows:"
)
(
df.
loc
[
:
,
[
'name'
,
'grade'
]
]
)
(
)
Combining a row slice and a column slice
(
"Select the name to score columns for indices 'b' to 'd':"
)
(
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:
df.loc['b', ['name', 'score']]Select specific columns of a specific row, returning a Series.df.loc[['a', 'c'], ['name', 'age']]Select multiple rows and columns, returning a DataFrame.df.loc[:, ['name', 'grade']]A colon means selecting all rows.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
(
"Students with scores greater than 85:"
)
(
df.
loc
[
df
[
'score'
]
>
;
85
]
)
(
)
Compound condition: score greater than 85 and age less than 19
(
"Students with scores greater than 85 and age less than 19:"
)
(
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:
df.loc[df['score'] > 85]Filter using boolean conditions, returning rows that satisfy the condition.- Compound conditions need to be enclosed in parentheses and joined with
&(and) and|(or). - You can pass a boolean array directly (its length must equal the number of rows) to select rows.
- A column selection can follow the condition to achieve fine-grained data filtering.
Notes
loc[]uses label indexing, and slices are inclusive of both ends (unlike native Python slices).- If a passed label does not exist, a KeyError will be raised.
- In boolean conditions, compound conditions must use parentheses and use
&and|instead of Python'sandandor。 loc[]Reading and modifying data is convenient, but be mindful of performance with large datasets.
Important note:
loc[]andiloc[]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.
Common Pandas functions