To find the absolute value in pandas, the easiest way is to use the pandas abs() function.
df["Column"] = df["Column"].abs()
You can also use the numpy abs() function and apply it to a column.
df["Column"] = df["Column"].apply(np.abs)
Finding the absolute value of numbers in a column, or the absolute value of all numbers in a DataFrame using pandas is easy. We can use the pandas abs() function to find the absolute values in a column of numbers, or a DataFrame.
Let’s say we have the following DataFrame.
df = pd.DataFrame({'Name': ['Jim', 'Sally', 'Bob', 'Sue', 'Jill', 'Larry'],
'Weight Change': [-16.20, 12.81, -20.45, 15.35, -12.43, -18.52]})
print(df)
# Output:
Name Weight Change
0 Jim -16.20
1 Sally 12.81
2 Bob -20.45
3 Sue 15.35
4 Jill -12.43
5 Larry -18.52
To get the absolute values of the numbers in the column “Weight Change”, we can use the pandas abs() function in the following Python code:
df["Weight Change"] = df["Weight Change"].abs()
print(df)
# Output:
Name Weight Change
0 Jim 16.20
1 Sally 12.81
2 Bob 20.45
3 Sue 15.35
4 Jill 12.43
5 Larry 18.52
As you can see above, all of the numbers are now positive.
Please note, you can use the pandas abs() function on an entire DataFrame if the DataFrame only contains numbers. If we call it on the DataFrame from above, we will receive an error because the “Name” column is made up of strings.
Using numpy abs to Calculate Absolute Values with pandas DataFrame
We can also use the numpy abs() function to calculate the absolute values of the numbers in a column in a pandas DataFrame.
To get the absolute values of the numbers in the column “Weight Change”, we can use the numpy abs() function in the following Python code:
df["Weight Change"] = df["Weight Change"].apply(np.abs)
print(df)
# Output:
Name Weight Change
0 Jim 16.20
1 Sally 12.81
2 Bob 20.45
3 Sue 15.35
4 Jill 12.43
5 Larry 18.52
As you can see above, all of the numbers are now positive.
One last thing to note, if you are looking to find the absolute value of a number in regular Python, you can use the Math.fabs() function.
Hopefully this article has been helpful for you to understand how to find the absolute value of numbers in a Series or DataFrame in pandas.