search
Search
Unlock 100+ guides
search toc
close
Cancel
Post
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

# NumPy | where method

schedule May 21, 2023
Last updated
local_offer
PythonNumPy
Tags
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

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]]) ```
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!