How to Use the Numpy absolute() Function in Python



In this article, you will learn how to use the Numpy absolute() function in Python.

Numpy absolute() Function

The numpy.absolute() function returns the absolute value of each element in an array. Here’s how you can use it in Python:

Import the numpy module:

import numpy as np

Create an array:

arr = np.array([-2, 0, 4, -6])

Use the absolute() function to get the absolute value of each element in the array:

abs_arr = np.absolute(arr)

Print the resulting array:


# Output: [2 0 4 6]

You can also use the np.abs() function to achieve the same result. For example:

arr = np.array([-2, 0, 4, -6])
abs_arr = np.abs(arr)

# Output: [2 0 4 6]

Both numpy.absolute() and numpy.abs() functions can be used interchangeably.


Here are some additional details about the numpy.absolute() function:

  • It can be used with arrays of any dimensionality.
  • It can be used with arrays of any numeric type, including integers, floats, and complex numbers.
  • If the input array contains complex numbers, the function returns the magnitude of each complex number. This is equivalent to computing the square root of the sum of the squares of the real and imaginary components of the complex number.
  • The function returns a new array that contains the absolute values of the input array elements. The input array itself is not modified.
  • The function can also be called using the alias numpy.abs().
  • The function can also be used with scalar values. For example, np.absolute(-2.3) returns 2.3.

Here are some examples of using the numpy.absolute() function with different input arrays:

import numpy as np

# 1D array of integers
arr1 = np.array([-1, 0, 1, -2, 3])
abs_arr1 = np.absolute(arr1)
print(abs_arr1)  # [1 0 1 2 3]

# 2D array of floats
arr2 = np.array([[1.2, -2.3], [-3.4, 4.5]])
abs_arr2 = np.absolute(arr2)
print(abs_arr2)  # [[1.2 2.3], [3.4 4.5]]

# 1D array of complex numbers
arr3 = np.array([1 + 2j, -2 - 3j, 4 + 0j])
abs_arr3 = np.absolute(arr3)
print(abs_arr3)  # [2.23606798 3.60555128 4.        ]