Python Absolute Value

Software Development
by: Ryan Ernst

The absolute value of a number is the non-negative value of a number without regard to its sign. This is often useful when you care more about the size of a value, you are calculating a delta from zero in either direction, or you are measuring something that is direction agnostic and only care about the magnitude.

 

In Python, to calculate the absolute value of a number you use the abs function. This is a Python built-in function that is always available.

abs(0.1)   # 0.1
abs(-0.1)  # 0.1
abs(-5)    # 5
abs(-1e3)  # 1000.0

 

Sometimes though you might need to get the absolute value from every element in a list. In this case, you can use a list expansion and abs:

[ abs(x) for x in [-1, 1, 2, -2] ] # [1, 1, 2, 2]

 

Maybe though you are using N-dimensional arrays (ndarrays) via NumPy, in that case, you can get the element-wise absolute value of a ndarray using numpy.absolute:

import numpy as np

np.absolute([ [-1,2], [2,-1] ]) # np.array([ [1, 2], [2, 1] ])

 

If you are using DataFrames in pandas, you can use the pandas.DataFrame.abs method:

import pandas as pd

df = pd.DataFrame({
    'a': [1, 2, -3],
    'b': [-4, 5, -6],
    'c': [7, 8, -9]
})

# returns:
#   a b c
# 0 1 4 7
# 1 2 5 8
# 2 3 6 9

 

Hopefully, this short little post has been helpful! If you have a topic you would like us to write about, or need help with a Python data project, please reach out at: tech@iq-inc.com!