當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Pandas Series.aggregate()用法及代碼示例

Pandas 係列是帶有軸標簽的一維ndarray。標簽不必是唯一的,但必須是可哈希的類型。該對象同時支持基於整數和基於標簽的索引,並提供了許多方法來執行涉及索引的操作。

Pandas Series.aggregate()函數在給定係列對象中的指定軸上使用一個或多個操作進行聚合。

用法: Series.aggregate(func, axis=0, *args, **kwargs)

參數:
func:用於匯總數據的函數。
axis:與DataFrame兼容所需的參數。
*args:位置參數傳遞給func。
**kwargs:傳遞給func的關鍵字參數。

返回:DataFrame,係列或標量

範例1:采用Series.aggregate()函數對給定係列對象的基礎數據執行聚合。

# importing pandas as pd 
import pandas as pd 
  
# Creating the Series 
sr = pd.Series([34, 5, 13, 32, 4, 15]) 
  
# Create the Index 
index_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] 
  
# set the index 
sr.index = index_ 
  
# Print the series 
print(sr)

輸出:

Coca Cola    34
Sprite        5
Coke         13
Fanta        32
Dew           4
ThumbsUp     15
dtype:int64

現在我們將使用Series.aggregate()函數以查找給定係列對象中所有值的總和。

# Find the sum of all values 
result = sr.aggregate(func = sum) 
  
# Print the result 
print(result)

輸出:

103

正如我們在輸出中看到的,Series.aggregate()函數已成功返回給定係列對象的基礎數據之和。

範例2:采用Series.aggregate()函數對給定係列對象的基礎數據執行聚合。

# importing pandas as pd 
import pandas as pd 
  
# Creating the Series 
sr = pd.Series([51, 10, 24, 18, 1, 84, 12, 10, 5, 24, 0]) 
  
# Create the Index 
# apply yearly frequency 
index_ = pd.date_range('2010-10-09 08:45', periods = 11, freq ='Y') 
  
# set the index 
sr.index = index_ 
  
# Print the series 
print(sr)

輸出:

2010-12-31 08:45:00    51
2011-12-31 08:45:00    10
2012-12-31 08:45:00    24
2013-12-31 08:45:00    18
2014-12-31 08:45:00     1
2015-12-31 08:45:00    84
2016-12-31 08:45:00    12
2017-12-31 08:45:00    10
2018-12-31 08:45:00     5
2019-12-31 08:45:00    24
2020-12-31 08:45:00     0
Freq:A-DEC, dtype:int64

現在我們將使用Series.aggregate()函數查找給定係列對象中所有值的最大值。

# Find the max of all values 
result = sr.aggregate(func = max) 
  
# Print the result 
print(result)

輸出:

84

正如我們在輸出中看到的,Series.aggregate()函數已成功返回給定係列對象中所有值的最大值。



相關用法


注:本文由純淨天空篩選整理自Shubham__Ranjan大神的英文原創作品 Python | Pandas Series.aggregate()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。