Module 2 · Beginner · Selecting and filtering data

Filter rows in pandas by conditions

Filter rows in a pandas DataFrame by conditions: comparisons, multiple conditions with & and |, isin, between, text matching, missing values, with examples.

By theprogrammers team · · 4 min read

Filtering means keeping only the rows that match a condition: orders above ₹1,000, students from one city, products that are out of stock. It's the pandas version of the filter button in Excel, and it's how almost every analysis starts.

This lesson shows how filtering works, then covers every kind of condition you'll need: comparisons, several conditions at once, lists of values, ranges, text and missing values.

Our example data is a small set of online orders:

import pandas as pd

orders = pd.DataFrame({
    "order_id": [101, 102, 103, 104, 105, 106, 107],
    "city":     ["Kanpur", "Delhi", "Kanpur", "Pune", "Delhi", "Lucknow", "Pune"],
    "category": ["Books", "Mobiles", "Fashion", "Books", "Fashion", "Mobiles", "Books"],
    "amount":   [450, 15999, 1200, 300, 2500, 9999, None],
    "paid":     [True, True, False, True, True, False, True],
})

How filtering works

A condition on a column gives a Series of True and False, one per row:

print(orders["amount"] > 1000)
0    False
1     True
2     True
3    False
4     True
5     True
6    False
Name: amount, dtype: bool

Put that inside orders[...] and pandas keeps the rows marked True:

big = orders[orders["amount"] > 1000]
print(big)
   order_id     city category   amount   paid
1       102    Delhi  Mobiles  15999.0   True
2       103   Kanpur  Fashion   1200.0  False
4       105    Delhi  Fashion   2500.0   True
5       106  Lucknow  Mobiles   9999.0  False

The original row labels (1, 2, 4, 5) are kept, so you can always trace a row back. Add .reset_index(drop=True) if you want 0, 1, 2… again. And the result is a new DataFrame: orders itself is unchanged.

Comparison operators

OperatorMeaningExample
==equal toorders["city"] == "Pune"
!=not equal toorders["city"] != "Pune"
>, >=greater than (or equal)orders["amount"] >= 500
<, <=less than (or equal)orders["amount"] < 500

A boolean column is already a condition, so you can use it directly: orders[orders["paid"]] keeps paid orders, and orders[~orders["paid"]] keeps unpaid ones. The ~ means "not".

Several conditions: & and |

Use & for "and" and | for "or", with brackets around each condition:

print(orders[(orders["city"] == "Delhi") & (orders["amount"] > 2000)])
   order_id   city category   amount  paid
1       102  Delhi  Mobiles  15999.0  True
4       105  Delhi  Fashion   2500.0  True
print(orders[(orders["category"] == "Books") | (orders["paid"] == False)])

Without the brackets, Python evaluates & before == and you get a confusing error. And Python's and/or don't work on whole columns: they raise ValueError: The truth value of a Series is ambiguous.

For long conditions, give each one a name. It reads like English and is easy to debug:

is_delhi = orders["city"] == "Delhi"
is_big = orders["amount"] > 2000
print(orders[is_delhi & is_big])

Match one of several values: isin

Instead of chaining | again and again, pass a list to isin:

print(orders[orders["city"].isin(["Kanpur", "Lucknow"])])
   order_id     city category  amount   paid
0       101   Kanpur    Books   450.0   True
2       103   Kanpur  Fashion  1200.0  False
5       106  Lucknow  Mobiles  9999.0  False

Add ~ for "not in the list": orders[~orders["city"].isin(["Kanpur", "Lucknow"])].

A range of values: between

between checks a range, including both ends by default:

print(orders[orders["amount"].between(1000, 10000)])
   order_id     city category  amount   paid
2       103   Kanpur  Fashion  1200.0  False
4       105    Delhi  Fashion  2500.0   True
5       106  Lucknow  Mobiles  9999.0  False

Text conditions

Text columns have a .str accessor with string methods that return True/False:

print(orders[orders["city"].str.startswith("L")])        # Lucknow
print(orders[orders["category"].str.contains("ob")])     # Mobiles
print(orders[orders["city"].str.lower() == "pune"])      # case-insensitive

str.contains also takes case=False to ignore case. If the column has missing values, add na=False, or the missing values cause an error.

Missing values

amount has a missing value for order 107. Find or skip missing values with isna and notna:

print(orders[orders["amount"].isna()])
   order_id  city category  amount  paid
6       107  Pune    Books     NaN  True

Remember that a comparison with a missing value is always False. orders["amount"] < 500 doesn't include order 107, and neither does orders["amount"] >= 500. If you split data into two groups with opposite conditions, the missing rows fall into neither.

Filtering and choosing columns together

To filter rows and pick columns in one step, use loc, explained in loc vs iloc in pandas:

print(orders.loc[orders["paid"], ["order_id", "amount"]])

Counting what matched

A condition is a column of True (1) and False (0), so you can count and measure without filtering:

print((orders["amount"] > 1000).sum())     # 4 big orders
print(orders["paid"].mean())               # 0.714...: 71% paid
print(len(orders[orders["city"] == "Delhi"]))    # 2

Practice

  1. Show the unpaid orders.
Show the answer
print(orders[~orders["paid"]])

Orders 103 and 106.

  1. Show Books or Fashion orders from Kanpur or Pune.
Show the answer
cat = orders["category"].isin(["Books", "Fashion"])
city = orders["city"].isin(["Kanpur", "Pune"])
print(orders[cat & city])

Orders 101, 103, 104 and 107.

  1. What is the total amount of paid orders between ₹400 and ₹5,000?
Show the answer
mask = orders["paid"] & orders["amount"].between(400, 5000)
print(orders.loc[mask, "amount"].sum())    # 2950.0

Orders 101 (450) and 105 (2500).

Interview questions

How do you filter a DataFrame with multiple conditions?

Combine boolean Series with & (and), | (or) and ~ (not), putting brackets around each condition: df[(df["a"] > 1) & (df["b"] == "x")]. Python's and/or raise an error because a Series has no single truth value.

What is the difference between isin and ==?

== compares to one value; isin checks membership in a list of values, replacing a chain of | conditions.

How do comparisons treat NaN in pandas?

Any comparison with NaN (except !=) is False, so NaN rows are dropped by both > x and <= x. Check them explicitly with isna() or notna().

What to learn next

  1. Write filters as readable strings with filter data with pandas query().
  2. Put the results in order with sort and rank data in pandas.