Python Absolute Value: Abs() in Python

Python Absolute Value Cover Image

In this tutorial, you’ll learn how to calculate a Python absolute value, using the abs() function. You’ll learn what the absolute value represents and how to calculate the absolute value. You’ll also learn how to calculate the absolute value in Python for integers, floats, and complex numbers. Finally, you’ll learn how to apply the absolute value function with some hands-on examples.

The Quick Answer: Use the abs() Function

Quick Answer - Python Absolute Value

What is an Absolute Value?

An absolute value is the distance between a number and 0 on the number line, meaning that it is the positive number of any integer, float, or complex number.

Some unique attributes of absolute numbers are:

  1. They are always non-negative (meaning, they are 0 or positive)
  2. The absolute value of a negative number is equal to the absolute value of its positive equivalent

Absolute numbers are often used in math, but also have many practical applications. For example, if you were to develop a program that was used to calculate the distance travelled over the course of a day, you would want to include “negative distance” (those travelled back). Because of this, you’d need to convert those negative numbers to positive numbers, to properly be able to add them up. This is where absolute numbers come in.

Let’s see how you can calculate an absolute value in Python by using the abs() function.

Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

Understanding the Abs() Function in Python

Python comes built-in with a function for calculating absolute values. This function is called the abs() function. The function takes a single parameter, either an integer, a floating point value, or a complex number. The function returns the absolute value of whatever number is passed into it.

abs(number)

Let’s see how we can use the abs() function to calculate an absolute value in Python.

Calculating Absolute Value in Python using Abs()

Let’s see how easy the abs() function is to use in Python to calculate the absolute value. We will pass in three examples: an integer, a floating point value, and a complex number.

Let’s get started:

# Calculating an Absolute Value in Python using abs()
integer1 = -10
integer2 = 22
float1 = -1.101
float2 = 1.234
zero = 0

print(abs(integer1))
print(abs(integer2))
print(abs(float1))
print(abs(float2))
print(abs(zero))

# Returns:
# 10
# 22
# 1.101
# 1.234
# 0

We can see here that by simply passing in an integer or a float, we are able to return its corresponding absolute value by using the Python abs() function.

In terms of passing in a complex number, the magnitude of that number is returned.

Let’s try another example where we pass in a complex number and see what is returns using the abs() function:

# Calculating the Magnitude of a Complex Number of abs()

complex_number = (3 - 4j)
print(abs(complex_number))

# Returns 5.0

In the next section, you’ll learn how to calculate an absolute value without the use of a function.

Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

Calculate the Python Absolute Value without a Function

There may be times when you’re challenged to find the absolute value of a given number without the use of the abs() function. This may come up in coding interviews or other challenge situations.

One way that we can accomplish this is to first square the number and then find its square root.

Let’s take a look at how we can do this:

# Calculating the Magnitude of a Complex Number of without a function

sample_number = -9.1
absolute_number = (sample_number ** 2) ** 0.5

print(absolute_number)

# Returns: 9.1

In the next section, you’ll learn how to calculate the absolute value of each number in a list.

Want to learn more about calculating the square root in Python? Check out my tutorial here, which will teach you different ways of calculating the square root, both without Python functions and with the help of functions.

Get the Absolute Value of a Python List

There may be many times when you’re presented with a list data structure that contains numbers and you want to convert all the numbers to their absolute values.

We can use either a for loop or a list comprehension to accomplish this. Lets first take a look at how to accomplish this using a for loop:

# Converting a Python lists' values to their absolute values using a for loop

sample_list = [-99, 123, -1.34, 3.14]

abs_list = list()
for value in sample_list:
    absolute = abs(value)
    abs_list.append(absolute)

print(abs_list)

# Returns: [99, 123, 1.34, 3.14]

Let’s break down what we’ve done here:

  1. We instantiated a new, empty list
  2. We looped over our list containing our numbers and calculated its absolute value using the abs() function
  3. We then append this number to our new list

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Now that we have a solid understanding of how to accomplish this using a for loop, let’s convert this into a Python list comprehension.

# Converting a Python lists' values to their absolute values using a list comprehension

sample_list = [-99, 123, -1.34, 3.14]

abs_list = [abs(item) for item in sample_list]
print(abs_list)

# Returns: [99, 123, 1.34, 3.14]

Using the list comprehension allows us to skip the step of instantiating an empty list, and can in this case be much easier to read.

In the next section you’ll learn how to calculate the absolute values of numbers contained in a numpy array.

Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.

Get the Absolute Value of a Numpy Array

Numpy arrays are list-like structures, but they come with a number of different built-in methods than Python lists do.

For example, one the numpy functions, np.abs(), takes a numpy array and converts all of its numbers to their absolute value.

Let’s take a look at an example of how we can accomplish this using numpy and Python:

# Converting a numpy array to absolute values
import numpy as np

sample_array = np.array([-99, 123, -1.34, 3.14])

abs_array = np.abs(sample_array)
print(abs_array)

# Returns: [ 99.   123.     1.34   3.14]

In the next section, you’ll learn how to convert a Pandas column to their absolute values.

Want to learn how to get a file’s extension in Python? This tutorial will teach you how to use the os and pathlib libraries to do just that!

Convert a Pandas Column to Absolute Values

Pandas makes it very easy to work with tabular data, storing the data in a pandas.DataFrame object. Let’s load a Pandas dataframe and learn how to convert a column’s values to their absolute values using built-in functions.

# Converting a Pandas dataframe column to its absolute values
import pandas as pd

df = pd.DataFrame({
    'Name': ['Nik', 'Kate', 'Michelle', 'Matt'],
    'Distance': [-100, 23, 1.02, -3.31]
})

df['Distance Absolute'] = df['Distance'].abs()

print(df)

# Returns:
#        Name  Distance  Distance Absolute
# 0       Nik   -100.00             100.00
# 1      Kate     23.00              23.00
# 2  Michelle      1.02               1.02
# 3      Matt     -3.31               3.31

Let’s explore what we did here:

  1. We loaded a sample dataframe
  2. We applied the .abs() to a column of data and assigned it to a new column to show its new transformations

Under the hood, Pandas uses the numpy method shown above to speed up its transformations.

Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

Conclusion

In this post, you learned how to calculate an absolute value using Python. You also learned how to manipulate Python list values to their absolute values, how to use the numpy.abs() function to convert an entire array to their absolute values, as well as how to convert Pandas dataframe columns to their absolute values.

To learn more about the abs() function in Python, check out the official documentation here.