How to obtain the absolute numeric value of DataFrame elements

Overview

In pandas, we use the abs() function to obtain the absolute numeric values of each element of a DataFrame or a Series object.

We can describe an absolute numeric value as the non-negative value of a number where we ignore its sign. For example, the absolute value of -1 is 1, and the absolute value of -10 is 10.

Syntax

The abs() function takes the syntax shown below:

DataFrame.abs()
Syntax for the abs() function in pandas

Parameter value

The abs() function takes no parameter value.

Return value

The abs() function returns a DataFrame or a Series object with each element’s absolute value in the input data.

Example

# A code to illustrate the abs() function in Pandas
# importing the pandas library
import pandas as pd
# creating a dataframe object
df = pd.DataFrame({
'row1': [1,-2,3,-4,5],
'row2': [6,-7,8,-9,10],
'row3': [-11,12,-13,14,-15]})
# printing the dataframe
print(df)
# obtaining the absolute values of each elements of the dataframe
print(df.abs())

Explanation

  • Line 4: We import the pandas library.
  • Lines 7–10: We create a DataFrame object, df.
  • Line 13: We print df.
  • Line 16: We obtain the absolute values of each element of df using the abs() function, and we print the result to the console.

Free Resources