w3resource

Pandas Series: abs() function

Pandas absolute value of column

The abs() function is used to get a Series/DataFrame with absolute numeric value of each element.

This function only applies to elements that are all numeric.

Syntax:

Series.abs(self)
Pandas Series abs image

Parameters: No parameters

Returns: Series/DataFrame containing the absolute value of each element.

Notes: For complex inputs, 1.2 + 1j, the absolute value is √a2+b2

Example - Absolute numeric values in a Series:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series([-2.8, 3, -4.44, 5])
s.abs()

Output:

0    2.80
1    3.00
2    4.44
3    5.00
dtype: float64

Example - Absolute numeric values in a Series with complex numbers:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series([2.2 + 1j])
s.abs()

Output:

0    2.416609
dtype: float64

Example - Absolute numeric values in a Series with a Timedelta element:

Python-Pandas Code:

import numpy as np
import pandas as pd
s = pd.Series([pd.Timedelta('2 days')])
s.abs()

Output:

0   2 days
dtype: timedelta64[ns]

Example - Select rows with data closest to certain value using argsort:

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame({
    'p': [2, 3, 4, 5],
    'q': [10, 20, 30, 40],
    'r': [200, 60, -40, -60]
})
df

Output:

  p	q	r
0	2	10	200
1	3	20	60
2	4	30	-40
3	5	40	-60

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame({
    'p': [2, 3, 4, 5],
    'q': [10, 20, 30, 40],
    'r': [200, 60, -40, -60]
})
df.loc[(df.r - 45).abs().argsort()]

Output:

   p   q    r
1  3  20   60
2  4  30  -40
3  5  40  -60
0  2  10  200

Previous: Exponential weighted functions in Pandas
Next: Test whether all element is true over requested Pandas axis



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/pandas/series/series-abs.php