Pandas Tutorial Pandas References

Pandas Series - abs() function



The Pandas Series abs() function returns a Series with absolute numeric value of each element. This function only applies to elements that are all numeric.

Syntax

Series.abs()

Parameters

No parameter is required.

Return Value

Returns rounded values of the Series.

Example: Applying on a Series

In the example below, the abs() function is used to get a Series with absolute numeric value of each element.

import pandas as pd
import numpy as np

x = pd.Series([-10, -20, 2, -5, 25])

print("The Series contains:")
print(x)

#Getting absolute value of all elements
print("\nx.abs() returns:")
print(x.abs())

The output of the above code will be:

The Series contains:
0   -10
1   -20
2     2
3    -5
4    25
dtype: int64

x.abs() returns:
0    10
1    20
2     2
3     5
4    25
dtype: int64

Example: Applying on selected series in a DataFrame

Similarly, the abs() function can be applied on selected series/column of a given DataFrame. Consider the following example.

import pandas as pd
import numpy as np

df = pd.DataFrame({
  "a": [5, -4, 2, -8],
  "b": [-10, -20, 2, -5],
  "c": [10, 20, -30, -5]
})

print("The DataFrame is:")
print(df)

#Applying on 'a' series
print("\ndf['a'].abs() returns:")
print(df["a"].abs())

The output of the above code will be:

The DataFrame is:
   a   b   c
0  5 -10  10
1 -4 -20  20
2  2   2 -30
3 -8  -5  -5

df['a'].abs() returns:
0    5
1    4
2    2
3    8
Name: a, dtype: int64

❮ Pandas Series - Functions

5