Finding Absolute Values For A Pandas Dataframe Object

Overview:

  • The absolute value of a real number is the distance from zero to its position in the number line. Hence, the real numbers -2 as well as +2 both will have the same distance of 2.
  • The absolute value is also called as modulus.
  • The absolute value of a complex number is given by the square root of the sum of squares of the real and the complex parts.

 

Calculating absolute value of a numeric values of a DataFrame using pandas:

  • DataFrame.abs() method finds the absolute value for each of the numeric element present in a DataFrame and returns them as another DataFrame.

Example:

import pandas as pd

numbers = [(-2, -1 , 0, 1, 2),  
           (-1.2, -1.1, 0.0, 1.1 ,1.2),
           ((-3.5 + 2j), (-3.5 - 2j), (3.5 + 2j), (2.5 - 2j), None)]

dataFrame = pd.DataFrame(data=numbers)
print("DataFrame:")
print(dataFrame)

print("Absolute values of the DataFrame:")
print(abs(dataFrame))

 

Output:

DataFrame:

           0          1         2         3    4

0    (-2+0j)    (-1+0j)        0j    (1+0j)  2.0

1  (-1.2+0j)  (-1.1+0j)        0j  (1.1+0j)  1.2

2  (-3.5+2j)  (-3.5-2j)  (3.5+2j)  (2.5-2j)  NaN

Absolute values of the DataFrame:

          0         1         2         3    4

0  2.000000  1.000000  0.000000  1.000000  2.0

1  1.200000  1.100000  0.000000  1.100000  1.2

2  4.031129  4.031129  4.031129  3.201562  NaN

 

 

 


Copyright 2022 © pythontic.com