How to get the absolute value of a dataframe column in pandas ?

Active November 29, 2021    /    Viewed 801    /    Comments 0    /    Edit


Examples of how to get the absolute value of a dataframe column in pandas:

Create a dataframe with pandas

Let's create first a dataframe with pandas:

import pandas as pd
import numpy as np

data = np.random.randint(-10,10, size=(5,4))

df = pd.DataFrame(data=data,columns=['a','b','c','d'])

returns for example

     a  b   c  d
0  1 -4   5 -3
1  4 -9  -4 -7
2 -7  6 -10  9
3  3 -5  -2  1
4  5 -5  -8  4

Apply abs() to one dataframe column

To get the absolute values over a dataframe column, a solution is to use pandas.DataFrame.abs :

df = df['b'].abs()

returns here

     a  b   c  d
0  1 4   5 -3
1  4 9  -4 -7
2 -7  6 -10  9
3  3 5  -2  1
4  5 5  -8  4

Apply abs() to multiple dataframe columns

Note that abs() can be applied to multiple columns:

cl = ['b','d']

df[ cl ] = df[ cl ].abs()

returns

     a  b   c  d
0  1  4   5  3
1  4  9  -4  7
2 -7  6 -10  9
3  3  5  -2  1
4  5  5  -8  4

Use abs() to filter the data

Another example on how to use abs() to filter the data:

df['c'][ df['c'].abs() <= 5 ] = -999

returns

     a  b    c  d
0  1  4 -999  3
1  4  9 -999  7
2 -7  6  -10  9
3  3  5 -999  1
4  5  5   -8  4

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount