Open In App

How to calculate the element-wise absolute value of NumPy array?

Let’s see the program for finding the element-wise absolute value of NumPy array. For doing this task we are using numpy.absolute() function of NumPy library. This mathematical function helps to calculate the absolute value of each element in the array.

Syntax: numpy.absolute(arr, out = None, ufunc ‘absolute’)



Return: An array with absolute value of each element.

Let’s see an example:



Example 1: Element-wise absolute value of 1d-array.




# import library
import numpy as np
  
# create a numpy 1d-array
array = np.array([1, -2, 3])
  
print("Given array:\n", array)
  
# find element-wise
# absolute value
rslt = np.absolute(array)
  
print("Absolute array:\n", rslt)

Output:

Given array:
[ 1 -2  3]
Absolute array:
[1 2 3]

Example 2: Element-wise absolute value of 2d-array.




# import library
import numpy as np
  
# create a numpy 2d-array
array = np.array([[1, -2, 3],
                  [-4, 5, -6]])
  
print("Given array:\n",
      array)
  
# find element-wise
# absolute value
rslt = np.absolute(array)
  
print("Absolute array:\n",
      rslt)

Output:

Given array:
[[ 1 -2  3]
[-4  5 -6]]
Absolute array:
[[1 2 3]
[4 5 6]]

Example 3: Element-wise absolute value of 3d-array.




# import library
import numpy as np
  
# create a numpy 3d-array
array = np.array([
    [[1, -2, 3],
     [-4, 5, -6]],
                   
    [[-7.5, -8.22, 9.0],
     [10.0, 11.5, -12.5]]
                 ])
  
print("Given array:\n",
      array)
  
# find element-wise
# absolute value 
rslt = np.absolute(array)
  
print("Absolute array:\n",
      rslt)

Output:

Given array:
[[[  1.    -2.     3.  ]
 [ -4.     5.    -6.  ]]

[[ -7.5   -8.22   9.  ]
 [ 10.    11.5  -12.5 ]]]
Absolute array:
[[[ 1.    2.    3.  ]
 [ 4.    5.    6.  ]]

[[ 7.5   8.22  9.  ]
 [10.   11.5  12.5 ]]]

Article Tags :