The square()
function computes squares of an array's elements.
Example
import numpy as np
array1 = np.array([1, 2, 3, 4])
# compute the square of array1 elements
result = np.square(array1)
print(result)
# Output: [ 1 4 9 16]
square() Syntax
The syntax of square()
is:
numpy.square(array, out = None, where = True, dtype = None)
square() Arguments
The square()
function takes following arguments:
array1
- the input arrayout
(optional) - the output array where the result will be storedwhere
(optional) - used for conditional replacement of elements in the output arraydtype
(optional) - data type of the output array
square() Return Value
The square()
function returns the array containing the element-wise squares of the input array.
Example 1: Use of dtype Argument in square()
import numpy as np
# create an array
array1 = np.array([1, 2, 3, 4])
# compute the square of array1 with different data types
result_float = np.square(array1, dtype=np.float32)
result_int = np.square(array1, dtype=np.int64)
# print the resulting arrays
print("Result with dtype=np.float32:", result_float)
print("Result with dtype=np.int64:", result_int)
Output
Result with dtype=np.float32: [ 1. 4. 9. 16.] Result with dtype=np.int64: [ 1 4 9 16]
Example 2: Use of out and where in square()
import numpy as np
# create an array
array1 = np.array([-2, -1, 0, 1, 2])
# create an empty array of same shape of array1 to store the result
result = np.zeros_like(array1)
# compute the square of array1 where the values are positive and store the result in result array
np.square(array1, where=array1 > 0, out=result)
print("Result:", result)
Output
Result: [0 0 0 1 4]
Here,
- The
where
argument specifies a condition,array1 > 0
, which checks if each element in array1 is greater than zero . - The
out
argument is set to result which specifies that the result will be stored in the result array.
For any element in array1 that is not greater than 0 will result in 0.