What is the use of abs() methods in pandas series?


The abs function of the pandas series will return a series with absolute numeric values of each element. This abs function will calculate the absolute values for each element in a series.

This function only works for a series objects if it has numerical elements only. it doesn’t work for any missing elements (NaN values), and it can be used to calculate absolute values for complex numbers.

Example

import pandas as pd

# create a series
s = pd.Series([-3.43, -6, 21, 6, 1.4])

print(s, end='

') # calculate absolute values result = s.abs() #print the result print(result)

Explanation

We have a simple pandas series object with 5 numerical elements, here our tack is to find the absolute values of our series elements. In order to calculate the absolute values, we need to have some negative values in our series, that’s why we have created a series with few negative values.

To find out the absolute values of an entire series, we can use the abs function to series object like ‘s.abs()’. So that this abs function will calculate the absolute values of each element in series.

Output

0   -3.43
1   -6.00
2   21.00
3    6.00
4    1.40
dtype: float64

0    3.43
1    6.00
2   21.00
3    6.00
4    1.40
dtype: float64

In the above block, we can see a series with negative values which is an initial one, and another series with absolute values that are calculated by using the abs() method.

Example

# importing pandas packages
import pandas as pd
import numpy as np


#creating a series with null data
s_obj = pd.Series([-2.3, np.nan, 9, 6.5, -5, -8, np.nan])

print(s_obj, end='

') #calculate absolute values result = s_obj.abs() #print the result print(result)

Explanation

This example is for calculating absolute values of a series with missing data (nothing but NaN ). To do this initially we have created a pandas series with some NAn values by using the NumPy.nan attribute.

Output

0   -2.3
1    NaN
2    9.0
3    6.5
4   -5.0
5   -8.0
6    NaN
dtype: float64

0   2.3
1   NaN
2   9.0
3   6.5
4   5.0
5   8.0
6   NaN
dtype: float64

Here we can see the output of the original series object as well as absolute values of each element in a series object.

Updated on: 18-Nov-2021

211 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements