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 libraryimport pandas as pd# creating a dataframe objectdf = pd.DataFrame({'row1': [1,-2,3,-4,5],'row2': [6,-7,8,-9,10],'row3': [-11,12,-13,14,-15]})# printing the dataframeprint(df)# obtaining the absolute values of each elements of the dataframeprint(df.abs())
Explanation
- Line 4: We import the pandas library.
- Lines 7–10: We create a
DataFrameobject,df. - Line 13: We print
df. - Line 16: We obtain the absolute values of each element of
dfusing theabs()function, and we print the result to the console.