How do you delete rows from a Pandas DataFrame based on a column condition? | A1Lab@MZeeshanM to PythonEnglish • 6 days ago

How do you delete rows from a Pandas DataFrame based on a column condition?

message-square
0

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 (==, <, >). Writing df[~df["price"] < 50] fails with TypeError: bad operand type for unary ~: 'float'; always write df[~(df["price"] < 50)].
  • Beware of df.drop() when the DataFrame has duplicate index labels: If two rows share index label 0 (for example, after pd.concat([df1, df2]) without ignore_index=True), df.drop(df[cond].index) deletes every row with index 0, even rows that did not satisfy cond. Boolean indexing (df = df[~cond]) evaluates row-by-row by position and never suffers from duplicate-index collisions.
  • How NaN values behave in negated conditions (~): Comparisons against np.nan always evaluate to False (e.g., np.nan < 50 is False), so inverting with ~(df["price"] < 50) turns False into True and retains rows where price is NaN. If you want to delete NaN rows 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 NaN safely): df = df[~df["product"].str.contains("Cable", na=False)]
  • 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 contiguous 0, 1, 2 index 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.