Convert DataFrame Column Values to Absolute Values

To convert DataFrame column values to absolute values:

df["column_name"] = df["column_name"].abs()

The Example

To start, create a DataFrame with a column that contains negative values.

Here, the “price” column contains two negative values:

import pandas as pd

data = {
"product_name": ["laptop", "printer", "tablet", "desk", "chair"],
"price": [1200, -200, -400, 300, 150],
}

df = pd.DataFrame(data)

print(df)

As highlighted in yellow, there are two negative values under the “price” column:

  product_name  price
0       laptop   1200
1      printer   -200
2       tablet   -400
3         desk    300
4        chair    150

Next, add the following syntax df[“price”] = df[“price”].abs() in order to convert the values under the “price” column to absolute values:

import pandas as pd

data = {
"product_name": ["laptop", "printer", "tablet", "desk", "chair"],
"price": [1200, -200, -400, 300, 150],
}

df = pd.DataFrame(data)

df["price"] = df["price"].abs()

print(df)

As you can see, the values under the “price” column are now in absolute terms:

  product_name  price
0       laptop   1200
1      printer    200
2       tablet    400
3         desk    300
4        chair    150

You can read more about this topic by visiting the Pandas Documentation.

Leave a Comment