numpy.square() function in Python
numpy.square() function in Python that calculates the square of each element in an input array, element-wise. It returns an array with
What it does :
It returns a new array with the squared values of the orignal array elements.
When to use it :
It is useful for squaring values in large datasets, or when you need to square each element in an array.
Syntax :
numpy.square(x, /, out=None, *, where=True)
Parameters :
- X : The input array whose element will be squared.
- Out : A location where the result will be stored.
- Where : A boolean array indicating where to calculate the results.
Returns :
Y : The squared value of the input x, returned as a NumPy array.
Example 1: Squaring a NumPy array.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
squared = np.square(arr)
print("Original Array:", arr)
print("Squared Array:", squared)
OutPut :
Original Array: [1 2 3 4 5]
Squared Array: [ 1 4 9 16 25]
Here is the breakdown of the following code, step by step :
- np.array([1, 2, 3, 4, 5]) creates a NumPy array with given values.
- np.square(arr) computes the square of each element in array : 1^2, 2^2, 3^2, 4^2, 5^2.
- The variable squared stores the squared results, while the original array remains unchanged.
Example 2 : Using the Out parameter.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
out_arr = np.empty_like(arr)
np.square(arr, out=out_arr)
print("Output Array:", out_arr)
OutPut :
Output Array: [ 1 4 9 16 25]
Here is the breakdown of the following code, step by step :
- np.empty_like(arr) : Creates an uninitialized array with the same shape and type as arr. This will serve as the output array.
- np.square(arr, out =out_arr) : Computes the square of each element in arr and stores the result in out_arr.
-
Example 3: Using the Where parameter.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
out_arr = np.copy(arr)
np.square(arr, out=out_arr, where=(arr % 2 == 0))
print("Conditionally Squared Array:", out_arr)
OutPut :
Conditionally Squared Array: [0 4 0 16 0]
Here is the breakdown of the following code, step by step :
- The condition (arr % 2 == 0) ensures squaring only even elements.
- The predefined output array, out_arr stores the result. The elements not satisfying the condition (arr % 2 ==0) remain unchanged.
ValueError: output array is required to use the 'where' parameter