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