How to calculate absolute value using Numpy

This Python guide introduces you to calculating the absolute value using Numpy, along with several practical techniques.

numpy absolute value

Basic Absolute Value Calculation

To calculate the absolute value of a number, the abs method is your straightforward option.

import numpy as np

my_scalar = -77

my_abs_value = np.abs(my_scalar)
print(f"My absolute value equals: {my_abs_value}")

For instance, the absolute value of -77 is 77.

You can also calculate the absolute values of arrays in a similar manner:

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}")

For example, the absolute values of an array containing (-1, -2) would be (1, 2).

See also  How to uninstall Numpy?

Regardless of the array’s size, the calculation remains the same:

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}")

numpy absolute value

Calculating Absolute Differences in Numpy Matrices

You can also compute the absolute difference between 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}")

np absolute difference

In this example, we’ve mapped two arrays and subtracted them using the np.abs() method. You can perform various calculations on Numpy arrays or matrices in a similar fashion.

See also  Calculate age from date of birth in Python

Numpy Functions for Absolute Value

Numpy provides two functions for absolute value calculations: np.abs() and np.absolute(). They are functionally identical, so choose the one that suits you best. I prefer np.abs() for its brevity, but the choice is yours.