Pandas loc[] Tutorial: Select Rows and Columns by Label
loc[] in Pandas is an indexer used to select rows and columns by their labels. It can retrieve one record, select particular columns, select a rectangular part of a DataFrame, filter rows with conditions, and update values. This comprehensive tutorial starts with the basic idea of labels and gradually moves to combined conditions, non-default indexes, assignment, and advanced selection patterns.
You should already know the basics of a Pandas DataFrame. If you are new to the library, begin with the introduction to Pandas. This page focuses specifically on loc[], rather than repeating installation or general DataFrame creation instructions.
- What is loc[]?
- Create a dataset for examples
- Understand the loc[] syntax
- Select a row by its label
- Select rows and columns together
- Select multiple rows or columns
- Label slicing and inclusive endpoints
- Filter rows using conditions
- Combine conditions with AND and OR
- Filter text and missing values
- Update values with loc[]
- Create or populate columns conditionally
- Use loc[] with custom indexes
- Introduction to MultiIndex selection
- loc[] vs iloc[] vs bracket selection
- Advanced patterns and practical case study
- Common errors and troubleshooting
- Practice exercises with solutions
- Frequently asked questions
1. What Is loc[] in Pandas?
loc[] is a label-based indexer. It tells Pandas which row labels and column labels you want. The square brackets are part of the syntax: write df.loc[...], not df.loc(...).
Imagine a spreadsheet with student records. The row labels might be 0, 1 and 2, while the column labels are Name, Age and Marks. You can use loc[] to request the record labelled 1, or the Name and Marks columns for that record.
| Term | Meaning | Example |
|---|---|---|
| Row label | The label identifying a row in the index. | 1 or "S102" |
| Column label | The name used to identify a column. | "Marks" |
| Label-based selection | Select by the labels, not by row position. | df.loc[1, "Marks"] |
| Boolean condition | A True/False test that determines which rows match. | df.loc[df["Marks"] >= 80] |
loc uses labels. iloc uses integer positions. A label can look like a number, but it is still treated as a label by loc[].2. Create a Dataset for the Examples
We will use a small student dataset throughout the tutorial. It contains a student ID, name, department, age, marks, attendance percentage and fee status. Keeping one consistent dataset makes it easier to understand each selection operation.
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
The default index labels are 0 through 5. The column labels are the names shown at the top. The StudentID values are currently ordinary data in a column; they are not the DataFrame index.
3. Understand the loc[] Syntax
The general form is:
df.loc[row_label, column_label]
The part before the comma identifies rows. The part after the comma identifies columns. If you omit the comma and second part, Pandas interprets the expression as row selection only.
| Expression | What it selects |
|---|---|
df.loc[2] | The row whose index label is 2. |
df.loc[2, "Name"] | The value in row label 2 and column Name. |
df.loc[2, ["Name", "Marks"]] | Two columns from row label 2. |
df.loc[2:4, "Name"] | Name values for labels 2, 3 and 4; the end label is included. |
df.loc[:, "Marks"] | Marks for all rows. |
df.loc[:, ["Name", "Marks"]] | Name and Marks for all rows. |
A colon (:) means “all labels in this direction” when used on its own. Therefore, df.loc[:, "Marks"] means all rows and the Marks column.
4. Select a Row by Its Label
Example 1: Select the row labelled 0
print(students.loc[0])
This returns a Series containing the values from Amina's record. The output is a vertical list because a single row selected this way is generally returned as a Series.
Example 2: Select another row
print(students.loc[3]) # Row labelled 3: Hamza
Example 3: Select one cell
print(students.loc[2, "Name"]) # Sara
print(students.loc[2, "Marks"]) # 94
When both a single row label and a single column label are provided, the result is a scalar value rather than a Series or DataFrame.
Example 4: Select a single row but keep a DataFrame
print(students.loc[[2]])
The extra pair of square brackets makes the row selector a list containing one label. The result is a one-row DataFrame. This can be useful when passing the result to code that expects a table.
5. Select Rows and Columns Together
One of the most useful features of loc[] is selecting a row and particular columns in one expression. This avoids selecting a full row and then extracting values separately.
Example 1: One row, one column
students.loc[1, "Department"]
Returns "Business", because row label 1 belongs to Bilal and his Department value is Business.
Example 2: One row, several columns
students.loc[1, ["Name", "Marks", "Attendance"]]
Example 3: All rows, one column
students.loc[:, "Name"]
This returns a Series containing the Name values for every row.
Example 4: All rows, multiple columns
students.loc[:, ["Name", "Department", "Marks"]]
Pass a list of column labels when you need more than one column. The order of the output columns follows the order in your list, not necessarily the original DataFrame order.
Example 5: A rectangular subset
students.loc[1:4, ["Name", "Marks"]]
This selects rows with labels 1, 2, 3 and 4, and only the Name and Marks columns. Because this is a label slice, both endpoint labels are included.
6. Select Multiple Rows or Columns
Choose specific row labels using a list
students.loc[[0, 2, 5]]
This selects rows labelled 0, 2 and 5. The requested order is preserved. You do not have to select a continuous range.
Select chosen rows and columns
students.loc[[0, 2, 5], ["StudentID", "Name", "Marks"]]
This is a convenient way to create a smaller report from a larger dataset, such as a list of selected students with their marks.
What if a requested label does not exist?
When a requested row or column label is missing, label-based selection normally raises a KeyError. For example, students.loc[99] fails because index label 99 is not present. Check labels with students.index and students.columns before selecting them.
7. Label Slicing and Inclusive Endpoints
For loc[], the end of a label slice is included when the endpoint exists. This differs from the usual Python list slice and from positional slicing with iloc[], where the stop position is excluded.
students.loc[1:3]
Rows labelled 1, 2 and 3 are returned. Compare this with students.iloc[1:3], which returns the rows at positions 1 and 2 only.
Slice rows and columns
students.loc[1:3, "Name":"Marks"]
The row labels 1 through 3 are included. The column slice from Name through Marks also includes its endpoint, following the order of the columns in the DataFrame. In this example it includes Name, Department, Age and Marks.
["Name", "Marks"] instead.8. Filter Rows Using Conditions
loc[] is not limited to index labels. You can pass a Boolean Series that contains True for rows to keep and False for rows to exclude. This is one of the most common ways to filter data in Pandas.
Example 1: Students with marks above 80
students.loc[students["Marks"] > 80]
Pandas evaluates students["Marks"] > 80 for every row. Rows with marks 88, 94 and 81 meet the condition, so only those records are returned.
Example 2: Select only useful columns from the matching rows
students.loc[students["Marks"] > 80, ["Name", "Marks"]]
This combines a row condition with a column selection: first specify the condition before the comma, then the columns after it.
Example 3: Marks at least 70
students.loc[students["Marks"] >= 70, ["StudentID", "Name", "Marks"]]
Example 4: Attendance below 80%
students.loc[students["Attendance"] < 80, ["Name", "Attendance"]]
Conditional selection is useful for identifying low attendance, overdue accounts, sales below a target, customers meeting eligibility rules or products requiring review.
9. Combine Conditions with AND and OR
You can combine several conditions. In Pandas, use & for element-wise AND and | for element-wise OR. Put parentheses around each comparison so that Python evaluates the conditions correctly.
Example 1: Marks at least 80 AND attendance at least 90
high_performers = students.loc[
(students["Marks"] >= 80) & (students["Attendance"] >= 90),
["Name", "Marks", "Attendance"]
]
print(high_performers)
A row must satisfy both conditions to be selected.
Example 2: Marks above 90 OR attendance above 90
selected = students.loc[
(students["Marks"] > 90) | (students["Attendance"] > 90),
["Name", "Marks", "Attendance"]
]
print(selected)
A row is selected if at least one condition is true.
Example 3: Exclude a condition with NOT
not_paid = students.loc[~students["FeePaid"], ["Name", "FeePaid"]]
The tilde (~) negates a Boolean Series. Here it selects rows where FeePaid is False. For a nullable Boolean column, decide explicitly how missing values should be treated.
Example 4: Filter within a numeric range
students.loc[
students["Marks"].between(70, 90),
["Name", "Marks"]
]
between(70, 90) includes both limits by default. It can make range conditions easier to read than writing two comparisons.
and or or directly between two Pandas Series. Use & and |, with parentheses around each comparison.10. Filter Text and Missing Values
Find rows matching a category
students.loc[students["Department"] == "Computing", ["Name", "Department"]]
Find text containing a word
students.loc[
students["Name"].str.contains("a", case=False, na=False),
["Name", "Department"]
]
The str.contains() method performs a text search. case=False makes the search case-insensitive, and na=False treats missing text as not matching. By default, the pattern is interpreted as a regular expression; use regex=False when you want a literal search string.
Find values that are missing
Suppose a DataFrame has missing marks. Use isna() to identify them and then pass that Boolean Series to loc[].
students.loc[students["Marks"].isna()]
To select rows where a value is present, use notna():
students.loc[students["Marks"].notna()]
The current sample has no missing Marks values, so the first expression returns an empty DataFrame. That is a valid result and indicates that no row meets the condition.
11. Update Values with loc[]
loc[] can assign values as well as retrieve them. Assignment is especially useful when a value needs correction or a group of records needs to be updated based on a rule.
Example 1: Update one cell
students.loc[1, "Marks"] = 70
print(students.loc[1, ["Name", "Marks"]])
This changes Bilal's Marks value at index label 1 to 70 in the DataFrame named students.
Example 2: Update several columns in one row
students.loc[1, ["Marks", "Attendance"]] = [75, 80]
The values on the right-hand side correspond to the selected columns in the same order. Ensure that the number and shape of assigned values are compatible with the selected cells.
Example 3: Update all rows meeting a condition
students.loc[students["Marks"] < 60, "Marks"] = 60
This sets Marks to 60 for every row whose current Marks value is below 60. It is a direct, readable way to make a conditional change.
Example 4: Update a category conditionally
students.loc[students["Attendance"] < 75, "FeePaid"] = False
This example illustrates the syntax rather than a recommended fee policy: it changes FeePaid to False for rows with attendance below 75. In real work, only update a field when the business rule genuinely justifies it.
df.loc[condition, "column"] = value to update the original DataFrame directly. Avoid chained assignment such as df[df["Marks"] < 60]["Marks"] = 60, which may not update the original object reliably and is incompatible with the intended copy-on-write model in modern Pandas.12. Create or Populate Columns Conditionally
Example 1: Create a new column and assign a default
students["Result"] = "Pass"
students.loc[students["Marks"] < 50, "Result"] = "Fail"
The first line creates a Result column and assigns Pass to every row. The second line changes the result to Fail for rows with marks below 50. This pattern is useful when a default category has a small number of exceptions.
Example 2: Assign different labels using multiple rules
students["Grade"] = "C"
students.loc[students["Marks"] >= 80, "Grade"] = "A"
students.loc[(students["Marks"] >= 70) & (students["Marks"] < 80), "Grade"] = "B"
Order matters when rules overlap. In this example, the default is C, marks of 80 or more become A, and marks from 70 up to but not including 80 become B. Define the rules carefully to avoid gaps or unintended overwrites.
Example 3: Set a value using a calculation
students.loc[students["Department"] == "Computing", "BonusMarks"] = (
students.loc[students["Department"] == "Computing", "Marks"] * 0.02
)
The right-hand side is a Series aligned by index labels. Pandas aligns labelled data during assignment. This is powerful, but it also means that indexes and shapes should be checked when assigning data from a different DataFrame.
13. Use loc[] with a Custom Index
The biggest conceptual challenge for beginners is that loc[] uses index labels rather than row positions. The difference becomes obvious when you use meaningful labels instead of the default numbers.
by_id = students.set_index("StudentID")
print(by_id.loc["S103"])
print(by_id.loc["S103", "Marks"])
After set_index("StudentID"), student IDs become the index labels. The label "S103" selects Sara's record, regardless of where that record appears in the current table.
Example: Select several IDs
by_id.loc[["S101", "S104", "S106"], ["Name", "Marks"]]
Example: Slice custom labels
Label slices are most straightforward when the index is ordered. With a sorted index, by_id.loc["S102":"S105"] selects labels from S102 through S105, including the endpoints when present. For an unsorted index, label slicing follows index ordering rules and may raise an error in some situations; sort the index if you need a predictable range.
by_id = by_id.sort_index()
by_id.loc["S102":"S105", ["Name", "Marks"]]
Reset the index when you need a regular column again
regular_table = by_id.reset_index()
print(regular_table.head())
14. Introduction to MultiIndex Selection
A MultiIndex is an index with more than one level. It can represent hierarchical labels, such as department and student ID, region and year, or store and product. loc[] can select using one or more levels.
records = pd.DataFrame(
{"Marks": [88, 67, 94, 72], "Attendance": [92, 78, 96, 83]},
index=pd.MultiIndex.from_tuples(
[("Computing", "S101"), ("Business", "S102"),
("Computing", "S103"), ("Business", "S104")],
names=["Department", "StudentID"]
)
)
print(records.loc["Computing"])
print(records.loc[("Computing", "S103"), "Marks"])
records.loc["Computing"] selects all records in the Computing level. A tuple such as ("Computing", "S103") identifies a particular combination of index labels. For complicated hierarchical slicing, consult the Pandas MultiIndex documentation and ensure the index is sorted where required.
15. loc[] vs iloc[] vs Ordinary Bracket Selection
These expressions can look similar, but they have different meanings. Choose the one that best communicates whether you are selecting by label, position or column name.
| Expression | Selection rule | Example |
|---|---|---|
df.loc["S103", "Marks"] | Row and column labels | Marks for index label S103 |
df.iloc[2, 4] | Zero-based row and column positions | Fifth column of third row |
df["Marks"] | Column label | Returns a Series |
df[["Name", "Marks"]] | List of column labels | Returns a DataFrame |
df.loc[condition] | Rows meeting a Boolean condition | Filtered DataFrame |
For example, if index labels are [10, 20, 30], then df.loc[20] selects the row labelled 20, while df.iloc[1] selects the second row by position. They may point to the same row in this example, but they express different selection rules.
example = pd.DataFrame(
{"Name": ["Amina", "Bilal", "Sara"], "Marks": [88, 67, 94]},
index=[10, 20, 30]
)
print(example.loc[20]) # Label 20: Bilal
print(example.iloc[1]) # Position 1: also Bilal
print(example.loc[20, "Marks"])
16. Advanced Patterns and a Practical Case Study
Pattern 1: Select rows using a condition stored in a variable
condition = (students["Marks"] >= 80) & (students["Attendance"] >= 85)
columns_to_show = ["StudentID", "Name", "Marks", "Attendance"]
report = students.loc[condition, columns_to_show]
print(report)
Separating a condition from the selection can improve readability when the same rule is used more than once. It also makes it easier to inspect the condition independently.
Pattern 2: Use query-like membership rules with isin()
departments = ["Computing", "Business"]
selected = students.loc[
students["Department"].isin(departments),
["Name", "Department", "Marks"]
]
isin() is useful when a value must belong to a set of allowed categories, IDs or statuses.
Pattern 3: Select rows based on a threshold calculated from the data
average_marks = students["Marks"].mean()
above_average = students.loc[
students["Marks"] > average_marks,
["Name", "Marks"]
]
print("Average:", average_marks)
print(above_average)
This calculates the mean first and then selects students whose marks exceed it. In a business dataset, the same pattern could identify transactions above average value or products with above-average sales.
Pattern 4: Select the top records after sorting
top_students = students.sort_values("Marks", ascending=False).loc[
:, ["Name", "Department", "Marks"]
].head(3)
print(top_students)
Here, sort_values() orders the DataFrame by Marks, loc[:, ...] selects the report columns, and head(3) returns the first three rows of the sorted result. This shows how loc[] fits into a longer data-analysis workflow.
Pattern 5: Use loc[] with a date index
daily_sales = pd.DataFrame(
{"Revenue": [1200, 1450, 980, 1670]},
index=pd.to_datetime(["2026-01-01", "2026-01-02", "2026-01-03", "2026-01-04"])
)
print(daily_sales.loc["2026-01-02"])
print(daily_sales.loc["2026-01-02":"2026-01-04"])
Datetime indexes support label-based selection by date. Partial date strings can select matching periods depending on the index type and its contents. For time-series work, ensure the index is a proper datetime index and consider sorting it before slicing.
Pattern 6: Use a condition to select rows, then update a column
students.loc[
(students["Marks"] >= 90) & (students["Attendance"] >= 90),
"Award"
] = "Distinction"
This is a common conditional-assignment pattern. If the Award column does not exist, Pandas creates it and fills rows that do not match with missing values. You may prefer to create a default value first if every row should have a defined category.
Business case study: Find high-value sales orders
Consider a sales DataFrame with order IDs, regions, order values and delivery status. The following example finds delivered orders worth at least 50,000 and returns only the columns needed for a management report.
orders = pd.DataFrame({
"OrderID": ["O501", "O502", "O503", "O504", "O505"],
"Region": ["North", "South", "North", "West", "South"],
"OrderValue": [72000, 35000, 51000, 88000, 64000],
"Status": ["Delivered", "Pending", "Delivered", "Delivered", "Cancelled"]
})
large_delivered = orders.loc[
(orders["OrderValue"] >= 50000) & (orders["Status"] == "Delivered"),
["OrderID", "Region", "OrderValue"]
]
print(large_delivered)
The condition combines a numeric threshold and a category match. This technique transfers directly to customer segmentation, finance reports, inventory analysis and operational dashboards.
17. Common loc[] Errors and How to Fix Them
Error 1: Using parentheses instead of square brackets
Incorrect: df.loc(2, "Name"). Correct: df.loc[2, "Name"]. loc is an indexer accessed with square brackets.
Error 2: Confusing a label with a position
If your index labels are strings, dates or numbers that are not sequential, df.loc[0] may not select the first displayed row. Use df.iloc[0] when you mean the first row by position.
Error 3: Forgetting parentheses around combined conditions
Incorrect: df.loc[df["Marks"] > 70 & df["Age"] < 23]. Correct:
df.loc[(df["Marks"] > 70) & (df["Age"] < 23)]
Error 4: Using and/or instead of &/|
Use & and | for Series comparisons. Python's scalar and and or cannot evaluate an entire Series as one truth value.
Error 5: Selecting a missing label
A misspelled column such as "mark" instead of "Marks" can produce a KeyError. Inspect df.columns and match the exact spelling and capitalisation.
Error 6: Accidentally changing the original data
Selection alone generally returns an object representing the requested data, but assignment through df.loc[...] = ... deliberately changes the DataFrame. If you want to preserve the original, make an explicit copy first, for example working = df.copy().
Error 7: Assignment alignment surprises
When assigning a Series, Pandas can align its values by index labels rather than simply by visible row order. If order matters, verify the indexes and shapes or use a carefully constructed array when positional assignment is intended.
18. Practice Exercises with Solutions
Try each exercise before opening its solution. Use the students DataFrame defined near the beginning of this page.
Exercise 1: Return the name of the student at index label 4.
Show solution
students.loc[4, "Name"]
The result is Noor.
Exercise 2: Select the Name and Marks columns for rows labelled 0, 2 and 4.
Show solution
students.loc[[0, 2, 4], ["Name", "Marks"]]
Exercise 3: Find students with marks of at least 80 and attendance below 95.
Show solution
students.loc[
(students["Marks"] >= 80) & (students["Attendance"] < 95),
["Name", "Marks", "Attendance"]
]
Exercise 4: Select only Business students who have paid their fees.
Show solution
students.loc[
(students["Department"] == "Business") & students["FeePaid"],
["Name", "Department", "FeePaid"]
]
Exercise 5: Set Attendance to 100 for Sara.
Show solution
students.loc[students["Name"] == "Sara", "Attendance"] = 100
This uses a condition rather than assuming Sara's row label will always remain 2.
Exercise 6: Select rows labelled 1 through 4, including both endpoints, and only the StudentID and Marks columns.
Show solution
students.loc[1:4, ["StudentID", "Marks"]]
19. Frequently Asked Questions About Pandas loc[]
What does loc[] mean in Pandas?
loc[] is a label-based indexer used to select rows and columns by their labels. It also supports Boolean conditions for filtering and assignment for updating values.
What is the syntax of loc[]?
The common syntax is df.loc[row_selector, column_selector]. The row selector can be a label, list, slice or Boolean condition. The column selector can be a column label, list or slice.
Does loc[] include the last value in a slice?
Yes. In a label slice such as df.loc[1:4], the stop label 4 is included when it exists. This differs from ordinary Python slicing and positional iloc[] slicing.
What is the difference between loc[] and iloc[]?
loc[] selects by labels; iloc[] selects by zero-based integer positions. Use the method that matches whether you know the label or the row/column position.
Can loc[] filter rows?
Yes. Pass a Boolean condition, such as df.loc[df["Sales"] > 1000], to return rows where Sales exceeds 1000. Combine conditions with & and |, using parentheses around each comparison.
Can loc[] change values?
Yes. An expression such as df.loc[df["Score"] < 50, "Result"] = "Review" assigns a value to rows meeting the condition.
Why does loc[] return a Series sometimes and a DataFrame other times?
Selecting one row or one column commonly returns a Series, while selecting multiple rows or columns returns a DataFrame. To keep a single row as a DataFrame, pass its label inside a list, such as df.loc[[2]].
Can I use loc[] with a string or date index?
Yes. It is designed for labels, so string IDs, dates and other index labels can be used directly. For date ranges, use a proper datetime index and keep the index ordered for predictable slicing.
Continue Learning Pandas
You have now learned how to use loc[] from basic label selection through conditional filtering, assignment and more advanced patterns. Continue with these related lessons:
