search
Search
Map of Data Science
Guest 0reps
exit_to_appLog out
Map of data science
Thanks for the thanks!
close
account_circle
Profile
exit_to_app
Sign out
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview Doc Search Code Search Beta SORRY NOTHING FOUND!
mic
Start speaking... Voice search is only supported in Safari and Chrome.
Shrink
Navigate to
A
A
brightness_medium
share
arrow_backShare Twitter Facebook

# NumPy | where method

NumPy
chevron_right
Documentation
schedule Jul 1, 2022
Last updated
local_offer PythonNumPy
Tags
expand_more
map
Check out the interactive map of data science

Numpy's `where(~)` method maps an array of booleans to the specified outputs, similar to how an `if-else` works.

# Parameters

1. `condition` | `array_like` of `booleans`

An array of booleans.

2. `x` | `array_like`

All instances of True will be replaced by x.

3. `y` | `array_like`

All instances of False will be replaced by y.

A Numpy array.

# Examples

## Basic mapping

To replace all `True` with 5, and all `False` with 10:

``` x = np.array([True, True, False, False])np.where(x, 5, 10) array([5, 5, 10, 10]) ```

On a more practical note, the `where()` method works well with a boolean mask. Suppose we wanted all values larger than 2 to be 10, and all other values to be -1.

We first build a boolean mask like follows:

``` x = np.array([1,2,3,4])mask = x > 2mask array([False, False, True, True]) ```

We then apply the mapping:

``` np.where(mask, 10, -1) array([-1, -1, 10, 10]) ```

## Replace values based on number

Suppose we wanted to perform some arithmetics based on a certain criteria. As an example, we want to add 5 to values larger than 2, and subtract by 5 otherwise:

``` x = np.array([1,2,3,4])np.where(x>2, x+5, x-5) array([-4, -3, 8, 9]) ```

## Multi-dimensional arrays

The method `where(~)` can also be used for multi-dimensional arrays:

``` x = np.array([[1,2],[3,4]])np.where(x>2, 10, 5) array([[5, 5], [10, 10]]) ```