📜  获取 Pandas 中的绝对值

📅  最后修改于: 2022-05-13 01:55:04.908000             🧑  作者: Mango

获取 Pandas 中的绝对值

让我们看看如何在Python Pandas 中获取元素的绝对值。我们可以使用abs()函数来执行此任务。 abs()函数用于获取具有每个元素的绝对数值的 Series/DataFrame。

示例 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())

输出 :

示例 2:具有复数的 Series 中的绝对数值。

# 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())

输出 :

示例 3:具有 Timedelta 元素的 Series 中的绝对数值。

# 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())

输出 :

示例 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())

输出 :