numpy.place in Python and Usage
In this article, we will learn about numpy.place 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-
- arr- Here we pass the array of which we want to change the value.
- mask – This takes the boolean condition based on which values of NumPy ndarray will be changed.
- 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 numpy.place
See the code below:
import numpy as np cd = np.array([2,1,2,3,4]) np.place(cd,cd==2,10) print(cd)
Here, we define three parameters inside the np.place() function.
- First parameter is our array cd.
- Second parameter is our boolean condition. cd==2 refers to all the values of the array cd.
- 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]
Now see another example:
import numpy as np cd2 = np.array([[1,2,3],[7,100,0]]) np.place(cd2,cd2<7,0) print(cd2)
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!