in Python and Usage

In this article, we will learn about in Python.

This function of the NumPy library can be used to change the values of a NumPy ndarray based on the condition given by the user.

It takes three parameters that are given below-

  1. arr- Here we pass the array of which we want to change the value.
  2. mask – This takes the boolean condition based on which values of NumPy ndarray will be changed.
  3. vals – These are the new values that will be replaced by the old values of the array based on the input condition.

Now, let’s understand it through some examples.

Python code examples of using

Example 1:

See the code below:

import numpy as np
cd = np.array([2,1,2,3,4]),cd==2,10)

Here, we define three parameters inside the function.

  1. First parameter is our array cd.
  2. Second parameter is our boolean condition. cd==2 refers to all the values of the array cd.
  3. Third parameter is the value that would be replacing all the values which satisfy the condition specified in the second parameter. This means all the values of the array cd which are equal to 2 will be replaced by the value 10.

This will give the following output that is given below:

[10 1 10 3 4]

Example 2:

Now see another example:

import numpy as np
cd2 = np.array([[1,2,3],[7,100,0]]),cd2<7,0)

In this example, all the numbers of the array which are less than 7 will be replaced with 0.
This gives the following output-

[[0 0 0]
 [7 100 0]]

I hope you all liked the article!

Also read: Python program to change the size of a NumPy array


Leave a Reply

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