Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk4 min

How to Replace Multiple Values in a Pandas DataFrame Based on Conditions

Choose between exact-value mappings and boolean rules to replace multiple pandas DataFrame values safely, with examples for .loc, where, mask, and numpy.select.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use DataFrame.replace() when you know the exact old values, and use a boolean condition with .loc, where(), or mask() when a rule determines which cells change. For multiple conditions that produce categories or labels, use numpy.select(). The right choice depends on whether you are matching values or evaluating a rule, and what should happen to cells that do not match.

Choose the method that matches your rule

What you need to do Use What happens outside the match
Replace known values such as old status codes wherever they occur DataFrame.replace() Unmatched values remain unchanged
Assign a fixed value to cells selected by a boolean rule Boolean mask with .loc Cells outside the mask remain unchanged
Keep values where a condition is true and replace the rest where() Uses the supplied replacement for false positions; without one, fills with a missing value
Replace values where a condition is true mask() Uses the supplied replacement at true positions
Choose among several condition-based results for a new column numpy.select() Uses the specified default if no condition matches
Apply ordered condition/replacement pairs to one Series Series.case_when() Returns a Series; check that the installed pandas version supports it

Replace several known values with DataFrame.replace()

When the old values are known in advance, pass a dictionary mapping each old value to its replacement. This matches values; it does not select rows based on an arbitrary condition.

out = df.replace({"old": "new", "legacy": "current"})

To make different substitutions in particular columns, nest the mappings under the column names:

out = df.replace({
    "status": {"N": "new", "C": "closed"},
    "priority": {"H": "high", "L": "low"}
})

Use regex mode only when you intend to match text patterns rather than exact values. The DataFrame.replace API reference documents the supported forms, including column-scoped mappings and regular-expression replacement.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Apply a boolean rule to selected cells

For a rule such as “set negative scores to zero,” create a boolean mask and assign through .loc. Naming the target column makes it clear which cells will change.

out = df.copy()
mask = out["score"] < 0
out.loc[mask, "score"] = 0

This changes the copy, leaving df available with its original values. If you intend to update the original DataFrame, assign to it directly instead of copying first. The pandas guide covers conditional selection and assignment alongside where and mask: Boolean indexing in the pandas user guide.

Make sure the condition selects the intended rows and that its index aligns with the DataFrame being assigned to. In particular, a mask built from one DataFrame should not be casually reused after changing the rows or index of another.

Choose between where() and mask()

The two methods have opposite condition polarity:

  • where(condition, other) keeps values where the condition is true and substitutes other where it is false.
  • mask(condition, other) substitutes other where the condition is true and keeps values where it is false.

For example, either of these replaces negative scores with zero:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
out["score"] = out["score"].where(out["score"] >= 0, 0)
out["score"] = out["score"].mask(out["score"] < 0, 0)

Choose the expression that makes the rule easiest to read. Omitting other from where() means failed positions are filled with a missing value: np.nan for NumPy dtypes and pd.NA for extension dtypes, according to the API documentation. Provide other explicitly if a missing result is not what you want. See the pandas references for DataFrame.where and DataFrame.mask.

Handle several conditions with numpy.select()

When each condition maps to a category and you want a result column, use numpy.select(conditions, choices, default=...). Conditions and choices correspond by position. For example, this classifies scores of 90 or higher as high, scores of 70–89 as medium, and the remaining scores as low:

Rank #4
Sale
Pandas Journal (Diary, Notebook)
  • Crisp writing pages are perfect for personal reflections, sketching, or for recording favorite quotations or poems.
  • Premium 120 gsm paper takes pen or pencil beautifully.
  • Paper is acid free and of archival quality.
  • Light gray lines subtly guide your writing.
  • An inside back cover pocket expands to hold notes, cards, mementos, and more.
import numpy as np

conditions = [df["score"] >= 90, df["score"] >= 70]
choices = ["high", "medium"]
out = df.assign(band=np.select(conditions, choices, default="low"))

Decide on the default deliberately: it determines the value for rows where no condition is true. Also consider overlapping conditions. If more than one rule can match the same row, arrange the rules with the intended priority; for example, test the higher threshold first as in the code above. The pandas guide to boolean indexing and conditional selection includes a multiple-condition example using NumPy selection.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use Series.case_when() for ordered rules on a Series

case_when() applies condition/replacement pairs to a Series and returns a Series; it is not a whole-DataFrame replacement method. It was added in pandas 2.2.0, so check the installed version before using it. The API result for pandas 3.0.3 identifies that version history. See the Series.case_when API reference for the supported syntax and behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Quick Recap

SaleBestseller No. 4
Pandas Journal (Diary, Notebook)
Pandas Journal (Diary, Notebook)
Premium 120 gsm paper takes pen or pencil beautifully.; Paper is acid free and of archival quality.
$10.99
Bestseller No. 5
Pandas Funny GIS/Programming/Python T-Shirt, Men, Black, Small
Pandas Funny GIS/Programming/Python T-Shirt, Men, Black, Small
Funny design. Import pandas as pd, an all too familiar python code.; Lightweight, Classic fit, Double-needle sleeve and bottom hem
$19.99
Best Value
Pandas Funny GIS/Programming/Python T-Shirt, Men, Black, Small
  • Funny design. Import pandas as pd, an all too familiar python code.
  • Featuring a familiar python code, this will get a laugh from all the nearby programmers and GIS professionals.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem

Common mistakes to avoid

  • Using replace() for a threshold: value mappings match specified values; use a boolean mask when the rule is something like “less than zero.”
  • Reversing where() and mask(): where() replaces false positions, while mask() replaces true positions.
  • Leaving unmatched results undefined: select a deliberate default for numpy.select(), and supply other to where() if missing values are not appropriate.
  • Overlooking version and scope: Series.case_when() acts on a Series and requires pandas 2.2.0 or newer.
  • Changing data you meant to preserve: copy the DataFrame before assignment when you need to retain the original.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.