Absolute Value of each Element in DataFrame

To compute the absolute value of each element of DataFrame in Pandas, call abs() method on this DataFrame.

In this tutorial, we will learn the syntax of abs() function and how to apply absolute function on each element of DataFrame.

Syntax

The syntax of abs() function is

</>
Copy
DataFrame.abs()

Return Value

abs() function returns a Series/DataFrame with absolute numeric value of each element from this DataFrame. This function only applies to elements that are all numeric in the given DataFrame.

Examples

Absolute Function on DataFrame with Numeric Values

In the following example, we take a DataFrame with numeric values, and apply absolute function to its elements.

Example.py

</>
Copy
import pandas as pd

df = pd.DataFrame(
    {'col1': [10, -20, -30], 'col2': [-40, 50, -60]})

result = df.abs()
print(result)

Output

   col1  col2
0    10    40
1    20    50
2    30    60

Absolute Value of DataFrame with Different Types of Values

In the following example, we take a DataFrame with a column of strings, and other column of integers. We shall call abs() method on this DataFrame.

Example.py

</>
Copy
import pandas as pd

df = pd.DataFrame(
    {'name': ["apple", "banana", "cherry"], 'quant': [-40, 50, -60]})

result = df.abs()
print(result)

Output

TypeError: bad operand type for abs(): 'str'

Absolute method works only with numeric elements. If the DataFrame contains elements of any other type, then TypeError would occur.

Conclusion

In this Pandas Tutorial, we learned how to find absolute value of each element of DataFrame using pandas DataFrame.abs() method.