In this Python lesson you will learn how to calculate absolute value using Numpy. You will get to know several useful tricks.
The easiest way to calculate the absolute value of a number is to use np.abs method and take the number as a parameter.
import numpy as np my_scalar = -77 my_abs_value = np.abs(my_scalar) print(f"My absolute value equals: {my_abs_value}")
As you can see the absolute value of -77 is 77.
You can always calculate abs value of an array similar way.
import numpy as np my_array = np.array([-1, -2]) my_abs_value = np.abs(my_array) print(f"My absolute value equals: {my_abs_value}")
The absolute value of an array of (-1, -2) is (1, 2).
No matter how big the array is you can calculate the same way.
import numpy as np my_array = np.array([[-1, -2], [3, -4], [-5, 6]]) my_abs_value = np.abs(my_array) print(f"My absolute value equals: \n{my_abs_value}")
Let’s see something more complicated and advanced.
How to calculate the absolute difference of Numpy matrices?
import numpy as np my_first_array = [[-2, -3, 4], [-4, 5, -6]] my_second_array = [[-1, 2, 7], [-8, 9, -9]] my_first_array, my_second_array = map(np.array, (my_first_array, my_second_array)) abs_difference = np.abs(my_first_array) - np.abs(my_second_array) print(f"The absolute difference between arrays equals: \n{abs_difference}")
I’ve just mapped two arrays and substracted them using np.abs() method. Similarly you may perform another calculations of numpy arrays or matrices.
You may also notice that Numpy offers two functions which you can use for absolute value calculations:
– np.abs()
– np.absolute()
They are exactly the same. It does not matter which one you will choose. I’m using np.abs() method because this one is the shorter one. It’s up to you which one you prefer. My recommendations is just to stick to the one of them.