NumPy Tutorial NumPy Statistics NumPy References

NumPy - power() function



The NumPy power() function is used to calculate first array elements raised to powers from second array, element-wise.

Syntax

numpy.power(x, y, out=None)

Parameters

x Required. Specify first array (array_like) containing elements as base.
y Required. Specify second array (array_like) containing elements as exponential. If x.shape != y.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
out Optional. Specify 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.

Return Value

Returns bases in x raised to the exponents in y.

Example: exponent as scalar

In the example below, numpy power() function is used to calculate the square and cube of each element of Arr.

import numpy as np

Arr = np.array([1, 2, 3, 4, 5])

print("The square of values:")
print(np.power(Arr, 2))

print("\nThe cube of values:")
print(np.power(Arr, 3))

The output of the above code will be:

The square of values:
[ 1  4  9 16 25]

The cube of values:
[  1   8  27  64 125]

Example: exponent as array

This example shows how to use exponent as array.

import numpy as np

base = np.array([5, 6, 7])
exponent = np.array([0, 1, 2])

print("The power of values:")
print(np.power(base, exponent))

The output of the above code will be:

The power of values:
[ 1  6 49]

❮ NumPy - Functions