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.
Python3
import numpy as np
array = np.array([ 1 , - 2 , 3 ])
print ( "Given array:\n" , array)
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.
Python3
import numpy as np
array = np.array([[ 1 , - 2 , 3 ],
[ - 4 , 5 , - 6 ]])
print ( "Given array:\n" ,
array)
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.
Python3
import numpy as np
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)
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 ]]]
Last Updated :
29 Aug, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...