October 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 NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Use np.where with Pandas in Python

Use np.where(condition, true_value, false_value) to create conditional pandas values, and choose where, select, or a Boolean mask when the task differs.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use np.where(condition, value_if_true, value_if_false) to create conditional values from pandas data. For example, assign its result to a DataFrame column to label each row according to a test on that row. Use numpy.select for several alternatives, Series.where or DataFrame.where to preserve the existing shape and values where a condition is true, and a Boolean mask to filter rows.

Use np.where to create a conditional column

Import NumPy, build a Boolean condition from a DataFrame column, and pass the condition and the two possible results to np.where. The pandas guide uses this pattern to add a new column:

import numpy as np

df['color'] = np.where(df['col2'] == 'Z', 'green', 'red')

Rows where col2 equals 'Z' get 'green'; rows where it does not get 'red'. The result is a conditional choice for each position in the condition, which you can assign to a new or existing column. See the pandas guide to indexing and selecting data.

Choose the operation that matches the result you need

Goal Use What happens
Create values from a true/false test np.where(condition, true_value, false_value) Chooses between two alternatives for each position; useful for a conditional column.
Keep the object’s shape, retaining values where a condition is true Series.where or DataFrame.where True positions keep their original values; false positions are replaced by other, or by a null value if no replacement is given.
Return only rows that match a condition df[mask] Selects a subset of rows instead of replacing values in the original shape.
Choose among more than two alternatives numpy.select(conditions, choices, default=...) Applies the corresponding choice for matching conditions and uses the specified fallback when none match.

The pandas indexing guide notes a useful signature distinction: df1.where(mask, df2) is roughly equivalent to np.where(mask, df1, df2). With pandas where, call the method on the values you want to keep; with NumPy, provide both alternatives.

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

Use multiple conditions with numpy.select

When a column needs three or more outcomes, pair an ordered list of conditions with a corresponding list of choices. Include a default for rows that do not meet any condition, so unmatched rows have an intentional value:

conditions = [df['score'] >= 90, df['score'] >= 70]
choices = ['high', 'medium']
df['rating'] = np.select(conditions, choices, default='low')

Conditions and choices correspond by position. The example tests the higher threshold first; rows not selected by either condition receive the default. This is the multi-option approach documented in the pandas guide.

Use pandas where to keep original values

If your goal is to preserve existing values wherever a condition is true and replace only the false positions, use where on the Series or DataFrame:

df['score'] = df['score'].where(df['score'] >= 0, other=0)

This keeps nonnegative scores and replaces negative ones with 0. Without an other value, false positions are replaced with a null value. Unlike a raw positional choice, pandas where considers index alignment for its condition and replacement; its dtype behavior also depends on whether a replacement can be cast losslessly to the caller’s dtype. Consult the DataFrame.where API reference for the documented alignment and dtype behavior, and check documentation for your installed pandas release when exact behavior matters.

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

Filter rows with a Boolean mask

If you want to remove nonmatching rows from the result rather than label or replace values, select with a Boolean mask:

adults = df[df['Age'] > 35]

This returns the rows whose Age is greater than 35. The pandas tutorial demonstrates this bracket-selection pattern for selecting a subset of a DataFrame.

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

Build conditions safely

Combine Series comparisons with elementwise operators

For multiple tests on pandas columns, use elementwise operators and parenthesize each comparison:

mask = (df['a'] > 0) & (df['b'] == 'x')
df['result'] = np.where(mask, 'match', 'other')

Do not combine Series conditions with Python’s scalar and or or; use & for elementwise AND and | for elementwise OR.

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

Check row correspondence when mixing pandas and NumPy

A Boolean Series carries an index, and pandas operations can align objects by index. A raw NumPy array is positional. When combining them or assigning a NumPy result, verify that the condition and the DataFrame rows have the intended order and compatible shape; otherwise, values can be associated with the wrong rows or fail to fit.

Check the resulting dtype

The true and false choices passed to np.where may lead to an output dtype different from the source column, particularly when the alternatives have different types. If dtype matters, inspect the assigned column after the operation. For pandas where, the caller’s dtype takes precedence when the replacement can be cast losslessly; incompatible replacements can change the resulting dtype. Consult documentation matching your installed pandas and NumPy versions, since the cited documentation pages describe versioned APIs.

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
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

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.