🐼 Python Pandas examples

pandas loc and iloc Examples

Select rows and columns by labels or positions using loc and iloc.

Updated 2026-06-125 practical examplesCopy-ready code

💡 Ideas for You

Learning resources for Python Pandas, data cleaning and analysis.

4 useful links

Some links in this section may be affiliate links. Choose only what is useful for your own work.

Sample DataFrame context

A DataFrame where you need precise row and column selection.

Syntax or pattern

df.loc[df["region"] == "East", ["product", "revenue"]]
✍️

5 practical examples

1

Filter high-value orders

Keep rows where revenue is above a threshold.

high_value = sales[sales["revenue"] > 1000]

The result contains only larger orders.

2

Filter by multiple conditions

Keep East region orders above 500.

filtered = sales[(sales["region"] == "East") & (sales["revenue"] > 500)]

Both conditions must be true.

3

Filter by a list

Keep selected regions.

selected = sales[sales["region"].isin(["East", "West"])]

The output contains only rows with those region values.

4

Filter text values

Find products containing a word.

matches = sales[sales["product"].str.contains("pro", case=False, na=False)]

This is useful for searching messy product names.

5

Select columns after filtering

Return only the fields needed for a report.

report = filtered[["order_id", "region", "product", "revenue"]]

The filtered output is easier to review or export.

Common mistakes to avoid

  • Changing the original DataFrame before checking the result.
  • Forgetting to inspect row counts before and after the operation.
  • Using a pattern without confirming column names and data types.

FAQ

What is the main use of loc and iloc Examples?

Select rows and columns by labels or positions using loc and iloc.

Should I use this in a notebook or a script?

Both work. Use a notebook while exploring the data, then move the final workflow into a repeatable script when it is stable.

How do I avoid breaking my source data?

Create a copy of the DataFrame before transforming it and check row counts, missing values and sample rows after each important step.