numpy.square() function in Python

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 :

  1. X :  The input array whose element will be squared.
  2. Out : A location where the result will be  stored.
  3. 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 :

  1. np.array([1, 2, 3, 4, 5]) creates a NumPy array with given values.
  2. np.square(arr) computes the square of each element in array : 1^2, 2^2, 3^2, 4^2, 5^2.
  3. 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 :

  1. np.empty_like(arr) : Creates an uninitialized array with the same shape and type as arr. This will serve as the output array.
  2. np.square(arr, out =out_arr) : Computes the square of each element in arr and stores the result in out_arr.
  3. The operation uses the out parameter to avoid creating a new array and stores the result directly in the provided memory location.

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 :

  1. The condition (arr % 2 == 0) ensures squaring only even elements.
  2. The predefined output array, out_arr stores the result. The elements not satisfying the condition            (arr % 2 ==0) remain unchanged.

If you skip the out parameter, then consequently, the code will throw an error similar to this :

ValueError: output array is required to use the 'where' parameter

numpy.square() function in Python

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top