NumPy absolute()

The absolute() function is used to compute the absolute value of each element in an array.

Example

import numpy as np

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

# use absolute() to find absolute values of each element in array1 result = np.absolute(array1)
print(result) # Output: [1 2 3 4 5]

absolute() Syntax

The syntax of absolute() is:

numpy.absolute(array, out=None)

absolute() Arguments

The absolute() function takes following arguments:

  • array - the input array whose absolute values is computed
  • out (optional) - the output array where the result is stored

absolute() Return Value

The absolute() function returns an array that contains the absolute value of each element in the input array.


Example 1: Find Absolute Values of 2D Array Elements

import numpy as np

# create a 2D array
array1 = np.array([[-1, 2, -3.5],
                                [4, -5, -6]])

# compute the absolute values of each element in array1 result = np.absolute(array1)
print(result)

Output

[[1.  2.  3.5]
 [4.  5.  6. ]]

Here, we have used the absolute() function to compute the absolute values of each element in the array1 array.

The absolute value of -1 is 1, 2 is 2, -3.5 is 3.5 and so on.


Example 2: Use out to Store Output in Desired Location

import numpy as np

# create an array
array1 = np.array([-12, 23, -25, -41, -52])

# create an empty array with the same shape as array1
result = np.zeros_like(array1)

# store the result in out_array np.absolute(array1, out=result)
print(result)

Output

[12 23 25 41 52]

Here, the absolute() function is used with the out parameter set to result. This ensures that the result of computing the absolute values is stored in result.


Example 3: Working With Complex Numbers

import numpy as np

complex_nums = np.array([3 + 4j, -2 - 5j, 1 + 1j])

# calculate absolute value of complex_nums result = np.absolute(complex_nums)
print(result)

Output

[5.         5.38516481 1.41421356]

Here, the absolute() function is applied to the complex_nums array, and it returns the array result containing the magnitudes of the complex numbers.

The magnitudes are calculated as the absolute values of the complex numbers using the formula:

√(a^2 + b^2)

Here, a and b are the real and imaginary parts of the complex number, respectively.