Advanced Data Filtering with pandas.query

Advanced Data Filtering with pandas.query

Pandas’ DataFrame.query() is useful when a filter reads like a sentence. Instead of repeating a dataframe name on every condition, put the expression in one string:

active_orders = orders.query("status == 'open' and total > 100")

The expression is evaluated against column names, so status and total refer to columns in orders. The result is a new dataframe containing the matching rows; the original dataframe is unchanged unless you assign the result back.

orders = orders.query("status == 'open' and total > 100")

Use and and or inside the query string. They work as row-wise logical operators here, unlike ordinary Python’s and and or, which cannot combine pandas Series.

recent_large_orders = orders.query(
    "status == 'open' and total > 100 and year >= 2024"
)

For a condition you have already computed, use @ to refer to a Python variable. This keeps changing values out of the expression text:

minimum_total = 250
wanted_status = "open"

matches = orders.query(
    "status == @wanted_status and total >= @minimum_total"
)

This is easier to read and safer than assembling a query string with string concatenation. Keep the expression itself under your control, and pass values through @variable rather than interpolating them into the query.

For a list of allowed values, in reads cleanly:

wanted_statuses = ["open", "pending"]

matches = orders.query("status in @wanted_statuses")

When a filter gets long, give each condition a name before combining it. A query is concise, but it should not become a puzzle whose logic must be decoded every time someone edits it.

minimum_total = 100
wanted_region = "west"

matches = orders.query(
    "status == 'open' and total >= @minimum_total and region == @wanted_region"
)

For column names that contain spaces or punctuation, surround the name with backticks inside the query expression:

matches = orders.query("order total > 100")

Backticks here are part of pandas’ query syntax, not Python string delimiters. The expression still needs ordinary Python quotes around string values, as in status == 'open'.

Getting column names to behave

A column name that’s also a Python keyword, such as class, needs the same treatment:

matches = students.query("class == 'advanced'")

Backticks also help when a column name contains punctuation that would otherwise be interpreted as part of the expression:

matches = measurements.query("temperature (C) >= 30")

They solve the parsing problem, not every naming problem. If a column name contains a backtick, or the expression becomes awkward to read, rename the column before querying:

clean = measurements.rename(columns={"temperature (C)": "temperature_c"})
matches = clean.query("temperature_c >= 30")

There is another possible source of confusion: a name in a query can refer to a column, while @name refers to a Python variable outside the dataframe. Make the distinction visible when both happen to have the same name:

threshold = 30

matches = measurements.query("threshold >= @threshold")

Here the left-hand threshold is a column and the right-hand @threshold is the Python variable. If that distinction makes the expression hard to scan, give the variable a more specific name:

minimum_temperature = 30

matches = measurements.query(
    "threshold >= @minimum_temperature"
)

For dataframes with complicated or inconsistent column names, a small rename step is often clearer than teaching every query reader the quirks of the original schema:

clean = raw.rename(
    columns={
        "Order Total ($)": "order_total",
        "Ship Date": "ship_date",
    }
)

late_orders = clean.query("order_total > 500")

Combining conditions without losing your place

Once a filter has more than one kind of logic, parentheses are cheap insurance. They make it obvious which conditions belong together, even when the query parser would apply its operator precedence correctly without them:

matches = orders.query(
    "(status == 'open' or status == 'pending') and total >= 100"
)

This keeps the status alternatives together: an order must have either status, and it must also meet the minimum total. Without the parentheses, the expression is easier to misread—and easier to change incorrectly.

For a longer expression, put the logical structure on separate lines inside the query string. The line breaks are for the person reading the code; the query still evaluates as one expression:

matches = orders.query(
    """
    (status == 'open' or status == 'pending')
    and total >= @minimum_total
    and region == @wanted_region
    """
)

Use parentheses around each group when mixing and and or. For example, this means an order qualifies if it’s either a large open order or a pending order from the wanted region:

matches = orders.query(
    """
    (status == 'open' and total >= @large_order_limit)
    or (status == 'pending' and region == @wanted_region)
    """
)

That grouping is the business rule. If the rule is hard to say aloud, split it into named intermediate dataframes rather than packing more logic into the query:

large_open = orders.query(
    "status == 'open' and total >= @large_order_limit"
)
regional_pending = orders.query(
    "status == 'pending' and region == @wanted_region"
)

matches = pd.concat([large_open, regional_pending])

When the groups can overlap, concatenating them may include the same row twice. In that case, a single grouped query avoids duplicates; alternatively, concatenate and remove duplicates only if the dataframe’s row identity makes that operation well-defined.

Keeping strings and dates on speaking terms

String comparisons in query() are exact. A value of "Open" does not match "open", and a trailing space is still part of the value. If the data comes from a CSV or another untidy source, normalize it before filtering:

orders["status"] = orders["status"].str.strip().str.lower()

open_orders = orders.query("status == 'open'")

For a value supplied by the caller, use @ rather than trying to nest Python quotes inside the query string:

wanted_region = "west"
matches = orders.query("region == @wanted_region")

Dates deserve more care. A column that merely looks like a date may still contain strings. Parse it once when the data enters the program, then compare it with a pandas timestamp:

orders["ship_date"] = pd.to_datetime(orders["ship_date"])

cutoff = pd.Timestamp("2025-01-01")
recent = orders.query("ship_date >= @cutoff")

Passing the cutoff as a variable avoids relying on string-to-date conversion inside the expression. It also makes the comparison explicit: the column and the boundary are both datetime values.

If the column contains missing or invalid dates, decide what those rows should mean before filtering. With the usual missing datetime value, a comparison such as ship_date >= @cutoff does not select the missing row.

orders["ship_date"] = pd.to_datetime(
    orders["ship_date"],
    errors="coerce",
)

dated_orders = orders.query("ship_date.notna() and ship_date >= @cutoff")

Timezone-aware timestamps must agree about their timezone. Convert the column and the comparison value to the same timezone before querying; comparing local timestamps to UTC values is not a formatting issue, but a question about which instant each value represents.

orders["ship_date"] = pd.to_datetime(
    orders["ship_date"],
    utc=True,
)

cutoff = pd.Timestamp("2025-01-01", tz="UTC")
recent = orders.query("ship_date >= @cutoff")

Knowing when query is the wrong tool

query() is a convenient expression parser, not a second Python interpreter. If the filter needs a method chain, a custom function, or several steps of data cleanup, ordinary pandas code is usually clearer:

normalized_status = orders["status"].str.strip().str.lower()
matches = orders.loc[
    normalized_status.eq("open")
    & orders["total"].ge(minimum_total)
]

That version makes each operation explicit. It also avoids trying to squeeze string methods into a query expression, where support depends on the expression and evaluation engine.

Use boolean masks when the rule is built dynamically, or when you need to inspect its pieces while debugging. A mask is just a Series of True and False values, so it can be named, tested, and reused:

is_open = orders["status"].eq("open")
is_large = orders["total"].ge(minimum_total)
is_recent = orders["ship_date"].ge(cutoff)

matches = orders.loc[is_open & is_large & is_recent]

Do not assume query() is faster because it looks shorter. It has parsing and evaluation costs, and the fastest choice depends on the data, expression, and pandas version. If performance matters, time both versions on representative data rather than choosing by appearance.

matches_query = orders.query(
    "status == 'open' and total >= @minimum_total"
)

matches_mask = orders.loc[
    orders["status"].eq("open")
    & orders["total"].ge(minimum_total)
]

A query string is executable expression text. Keep that text fixed in your program and pass changing values through @variable. Do not build expressions by inserting untrusted input into the string; use ordinary comparisons and masks when the user is choosing columns or operators.

# Keep the expression fixed; pass the value separately.
matches = orders.query("status == @wanted_status")

For a simple comparison across a few columns, a query is pleasant. For validation, custom transformations, complicated missing-value rules, or logic assembled from user choices, explicit pandas operations make the boundaries easier to see.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *