Numpy place: How to Use np place() Method in Python
Numpy place() function makes changes in the array according to the conditions and value of the parameters (uses first N-values to put into an array as per a mask being set by the user).
Numpy place(array, mask, vals) function make changes in the array according to the parameters – conditions and value(uses first N-values to put into an array as per the mask being set by the user). It works opposite to numpy.extract().
The place() function is defined under Numpy, which can be imported as import NumPy as np, and we can create multidimensional arrays and derive other mathematical statistics.
numpy.place(array, mask, vals)
array: This depicts the input array in which changes had to be made.
mask: It describes the Boolean condition. It must have the same size as that of the input array
value: It represents the values that are to be added to the array. Based on a mask condition, it adds only N-items to the array. If in case values in value are smaller than the mask, then the same values get repeated.
NumPy place() function returns the modified array, which was given at the time of input with added values according to the mask.
Write a program to show the working of Numpy place function.
import numpy as np array = np.arange(12).reshape(3, 4) print("Original array : \n", array) # Putting new elements a = np.place(array, array > 5, [10, 15, 25]) print("\nPutting up elements to array: \n", array)
Original array : [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] Putting up elements to array: [[ 0 1 2 3] [ 4 5 10 15] [25 10 15 25]]
In the above code, the original array whose elements were greater than 5 were replaced by the values [10,15,25]. When the list was completed. Then it was repeated.
See the following code.
import numpy as np array = np.arange(6).reshape(2, 3) print("\n\nOriginal array : \n", array) # Putting new elements a = np.place(array, array > 6, [22, 55]) print("\nPutting new elements to array : \n", array)
Original array : [[0 1 2] [3 4 5]] Putting new elements to array : [[0 1 2] [3 4 5]]
In this, the original array was returned at the output.
This happened because the mask condition was given to modify the elements whose values were greater than 5, as there were no elements within the array.
So, the original array was returned with no modifications.