Filter the DataFrame using boolean indexing with the inverted condition (df = df[~condition] or df = df[df["col"] >= value]), or pass the matching row index labels to df.drop(df[condition].index)—preferring boolean indexing because it is faster, avoids duplicate-index pitfalls, and chains cleanly.
Basic Example
import pandas as pd
df = pd.DataFrame({
"product": ["Laptop", "Mouse", "Monitor", "Cable", "Keyboard"],
"price": [1200, 25, 350, 10, 80],
"in_stock": [True, False, True, False, True],
})
# 1. Recommended: Boolean indexing (keep rows that do NOT match the deletion condition)
# Delete rows where price < 50
df_filtered = df[df["price"] >= 50]
print(df_filtered)
# 2. Compound condition using '~' (NOT), '&' (AND), '|' (OR) with parentheses
# Delete rows where (price < 50) OR (in_stock is False)
df_strict = df[~((df["price"] < 50) | (~df["in_stock"]))]
print(df_strict)
# 3. Alternative: df.drop() using the matching index labels
df_dropped = df.drop(df[df["price"] < 50].index)
Output (df_filtered):
product price in_stock
0 Laptop 1200 True
2 Monitor 350 True
4 Keyboard 80 True
Key Details & Edge Cases
- Always wrap compound conditions in parentheses
(...): Python’s bitwise operators (,|,~) have higher operator precedence than comparison operators (==,<,). Writingdf[~df["price"] < 50]fails withTypeError: bad operand type for unary ~: 'float'; always writedf[~(df["price"] < 50)]. - Beware of
df.drop()when the DataFrame has duplicate index labels: If two rows share index label0(for example, afterpd.concat([df1, df2])withoutignore_index=True),df.drop(df[cond].index)deletes every row with index0, even rows that did not satisfycond. Boolean indexing (df = df[~cond]) evaluates row-by-row by position and never suffers from duplicate-index collisions. - How
NaNvalues behave in negated conditions (~): Comparisons againstnp.nanalways evaluate toFalse(e.g.,np.nan < 50isFalse), so inverting with~(df["price"] < 50)turnsFalseintoTrueand retains rows wherepriceisNaN. If you want to deleteNaNrows as well, combine with.notna()(df[(df["price"] >= 50) & df["price"].notna()]). - String & membership conditions (
.isin(),.str.contains()):- Delete rows matching a list of values:
df = df[~df["status"].isin(["cancelled", "refunded"])] - Delete rows containing a substring (handling
NaNsafely):df = df[~df["product"].str.contains("Cable", na=False)]
- Delete rows matching a list of values:
- Resetting the index after row deletion: Both boolean filtering and
df.drop()preserve original index labels (0, 2, 4). Chain.reset_index(drop=True)if you need a contiguous0, 1, 2index afterward (df = df[df["price"] >= 50].reset_index(drop=True)).
Comparison of Conditional Row Deletion Methods in Pandas
| Method | Syntax | Safe With Duplicate Indices? | Chainable? | Best Used When |
|---|---|---|---|---|
| Boolean Indexing (Keep/Negate) | df = df[~(df["col"] < 50)] |
Yes | With .loc[...] |
Standard, fastest, and safest way to delete rows matching any condition. |
df.query() |
df = df.query("price >= 50 and in_stock") |
Yes | Yes | Clean, readable multi-column conditions inside method-chaining pipelines. |
df.drop(df[cond].index) |
df = df.drop(df[df["col"] < 50].index) |
No (drops all rows sharing a matching index label) | Yes | Explicitly removing rows by index label on uniquely indexed DataFrames. |
df.loc[lambda d: ...] |
df.loc[lambda d: d["price"] >= 50] |
Yes | Yes | Filtering mid-pipeline without storing intermediate DataFrame variables. |
You must log in or register to comment.
