Return the element-wise square of the array input in Python


To return the element-wise square of the array input, use the numpy.square() method in Python. The method returns the element-wise x*x, of the same shape and dtype as x. This is a scalar if x is a scalar.

The 1st parameter, x is the input data. The 2nd parameter, out is a location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned. A tuple (possible only as a keyword argument) must have length equal to the number of outputs.

The 3rd parameter, where, this condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

Steps

At first, import the required libraries-

import numpy as np

Creating a numpy array using the array() method. We have added elements of int type −

arr = np.array([[25, -50, 75], [-90, 81, 64]])

Display the array −

print("Our Array...\n",arr)

Check the Dimensions −

print("\nDimensions of our Array...\n",arr.ndim)

Get the Datatype −

print("\nDatatype of our Array object...\n",arr.dtype)

To return the element-wise square of the array input, use the numpy.square() method. The method returns the element-wise x*x, of the same shape and dtype as x. This is a scalar if x is a scalar −

print("\nResult...\n",np.square(arr))

Example

import numpy as np

# Creating a numpy array using the array() method
# We have added elements of int type
arr = np.array([[25, -50, 75], [-90, 81, 64]])

# Display the array
print("Our Array...\n",arr)

# Check the Dimensions
print("\nDimensions of our Array...\n",arr.ndim)

# Get the Datatype
print("\nDatatype of our Array object...\n",arr.dtype)

# To return the element-wise square of the array input, use the numpy.square() method in Python
# The method returns the element-wise x*x, of the same shape and dtype as x. This is a scalar if x is a scalar.
print("\nResult...\n",np.square(arr))

Output

Our Array...
[[ 25 -50 75]
[-90 81 64]]

Dimensions of our Array...
2

Datatype of our Array object...
int64

Result...
[[ 625 2500 5625]
[8100 6561 4096]]

Updated on: 25-Feb-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements