在Pandas中获取绝对值

在Pandas中获取绝对值

让我们看看如何在Python Pandas中获得一个元素的绝对值。我们可以通过使用abs()函数来完成这个任务。abs()函数是用来获取一个系列/数据框架中每个元素的绝对数值。

语法: Series.abs()或DataFrame.abs()
参数 :无
返回:系列/数据帧,包含每个元素的绝对值。

例子1:系列中的绝对数值。

# import the library
import pandas as pd
  
# create the Series
s = pd.Series([-2.8, 3, -4.44, 5])
print(s)
  
# fetching the absolute values
print("\nThe absolute values are :")
print(s.abs())

输出 :
在Pandas中获取绝对值

例子2 :绝对数值系列中的复数。

# import the library
import pandas as pd
  
# create the Series
s = pd.Series([2.2 + 1j])
print(s)
  
# fetching the absolute values
print("\nThe absolute values are :")
print(s.abs())

输出 :
在Pandas中获取绝对值

例子3:带有Timedelta元素的系列中的绝对数字值。

# import the library
import pandas as pd
  
# create the Series
s = pd.Series([pd.Timedelta('2 days')])
print(s)
  
# fetching the absolute values
print("\nThe absolute values are :")
print(s.abs())

输出 :
在Pandas中获取绝对值

示例4 :从DataFrame列中获取绝对值。

# import the library
import pandas as pd
  
# create the DataFrame
df = pd.DataFrame({'p' : [2, 3, 4, 5],
                   'q' : [10, 20, 30, 40],
                   'r' : [200, 60, -40, -60]})
display(df)
  
# fetching the absolute values
print("\nThe absolute values are :")
display(df.r.abs())

输出 :
在Pandas中获取绝对值

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程