Pandas Series abs() Method
In this tutorial, we will discuss and learn the panda's Series.abs()
method. By using this method, we can find the absolute value of any number and when this method applied to the Series
, it returns the Series that consists of the absolute value of elements.
This method is applicable to the elements that are only numeric and for the complex inputs, the absolute value will be a2+b2
.
The below is the syntax of the Series.abs()
method.
Syntax
abs(x)
Here, parameter x
can be any number and that can be a positive or negative zero. This method will return a positive zero.
Example: Getting the absolute value of the Series
Let's apply this method to the Series and get the absolute value and the code snippet for the same is as follows.
#importing pandas as pd
import pandas as pd
#creating Series
s = pd.Series([12,-0.25,-54])
print("-----Series-----")
print(s)
print("-------------------")
print(abs(s))
-----Series-----
0 12.00
1 -0.25
2 -54.00
dtype: float64
-------------------
0 12.00
1 0.25
2 54.00
dtype: float64
Example: TypeError while getting the absolute value of the string
As we discussed earlier the Series.abs()
method applies to the only numeric elements. Here, in this example, we are trying to get the absolute value for the Series that contains the string
elements and the Series.abs()
raise TypeError. See the below example.
#importing pandas as pd
import pandas as pd
#creating Series
s = pd.Series(['a','2','-0.32'])
print(abs(s))
TypeError: bad operand type for abs(): 'str'
Example: Getting the absolute value of DataFrame
Here, in this example, we will get the absolute value of the Series elements consisting of the complex numbers. For the complex inputs, the absolute value will be ?a2+b2
the Series.abs()
method returns only the magnitude part of the number.
#importing pandas as pd
import pandas as pd
#creating Series
s = pd.Series([2.1 + 1j,-20,-11])
print("-----Series-----")
print(s)
print("-------------------")
print(abs(s))
-----Series-----
0 2.100000+1.000000j
1 -20.000000+0.000000j
2 -11.000000+0.000000j
dtype: complex128
-------------------
0 2.325941
1 20.000000
2 11.000000
dtype: float64
Conclusion
In this tutorial, we understand the abs()
method of the data frame. We learned the syntax and parameters of Series.abs()
method and solve different examples to better understand this topic.