Absolute value for a column

Given a pandas dataframe, we have to find the absolute value for a column. By Pranit Sharma Last updated : October 03, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

The absolute value of any data (number) refers to the magnitude of that value, despite of the fact whether it is positive or negative.

Finding the absolute value for a column

So, if we are given with a DataFrame with multiple columns and one column contains some negative values, we need to convert them into positive values, this is called finding an absolute value i.e. if a value is negative then the same value without a negative sign is called its absolute value.

We can simply do this by multiplying each negative value by -1 but it will take a lot of time and hence pandas provide us with another method for finding absolute value. We will use the .abs() method to convert the actual value into absolute value.

Let us understand with the help of an example,

Python program to find the absolute value for a column

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'c':[1, -1, 2, -2, 3, -3]

# Creating DataFrame
df = pd.DataFrame(d)

# Display original DataFrame
print("Original DataFrame:\n",df,"\n")

# finding absolute values for column c
df['c'] = df['c'].abs()

# Display Result


The output of the above program is:

Example: Absolute value for a column

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.