NumPy square()
The numpy.square()
function computes the element-wise square of the input array, returning the squared values of each element.
Syntax
</>
Copy
numpy.square(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)
Parameters
Parameter | Type | Description |
---|---|---|
x | array_like | Input data whose elements will be squared. |
out | ndarray, None, or tuple of ndarray and None, optional | Optional output array where the result is stored. If None, a new array is created. |
where | array_like, optional | Boolean mask specifying which elements should be squared. Elements where where=False retain their original value. |
casting | str, optional | Defines the casting behavior when computing the square function. |
order | str, optional | Memory layout order of the output array. |
dtype | data-type, optional | Defines the data type of the output array. |
subok | bool, optional | Determines if subclasses of ndarray are preserved in the output. |
Return Value
Returns an array containing the element-wise square of the input values. If the input is a scalar, a scalar is returned.
Examples
1. Squaring a Single Value
Here, we compute the square of a single number using numpy.square()
.
</>
Copy
import numpy as np
# Define a number
num = 5
# Compute the square
result = np.square(num)
# Print the result
print("Square of", num, ":", result)
Output:
Square of 5 : 25

2. Squaring an Array of Values
We compute the square of multiple elements in an array.
</>
Copy
import numpy as np
# Define an array of numbers
arr = np.array([1, 2, 3, 4, 5])
# Compute the square of each element
squared_values = np.square(arr)
# Print the results
print("Original array:", arr)
print("Squared values:", squared_values)
Output:
Original array: [1 2 3 4 5]
Squared values: [ 1 4 9 16 25]

3. Using the out
Parameter
Using an output array to store results instead of creating a new array.
</>
Copy
import numpy as np
# Define an array of numbers
arr = np.array([2, 4, 6, 8])
# Create an output array with the same shape
output_array = np.empty_like(arr)
# Compute square and store the result in output_array
np.square(arr, out=output_array)
# Print the results
print("Computed squared values:", output_array)
Output:
Computed squared values: [ 4 16 36 64]

4. Using the where
Parameter
Using a condition to square only selected elements.
</>
Copy
import numpy as np
# Define an array of numbers
arr = np.array([1, 2, 3, 4, 5])
# Define a mask (square only elements greater than 2)
mask = arr > 2
# Compute squared values where mask is True
result = np.square(arr, where=mask)
# Print the results
print("Computed squared values with mask:", result)
Output:
Computed squared values with mask: [1 2 9 16 25]

The square operation is applied only to elements greater than 2. The remaining values remain unchanged.