Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →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.
#1 Best Overall
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.
Rank #2
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.
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.
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.
Best Value
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.
Quick Recap
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.




