Python | Панды Series.aggregate ()

Опубликовано: 27 Марта, 2022

Серия Pandas - это одномерный массив ndarray с метками осей. Этикетки не обязательно должны быть уникальными, но должны быть хешируемого типа. Объект поддерживает индексирование как на основе целых чисел, так и на основе меток и предоставляет множество методов для выполнения операций, связанных с индексом.

Pandas Series.aggregate() function aggregate using one or more operations over the specified axis in the given series object.

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

Parameter :
func : Function to use for aggregating the data.
axis : Parameter needed for compatibility with DataFrame.
*args : Positional arguments to pass to func.
**kwargs : Keyword arguments to pass to func.

Returns : DataFrame, Series or scalar

Example #1: Use Series.aggregate() function to perform aggregation on the underlying data of the given series object.

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

Выход :

 Кока-Кола 34
Спрайт 5
Кокс 13
Фанта 32
Роса 4
Большой палец вверх 15
dtype: int64

Now we will use Series.aggregate() function to find the sum of all the values in the given series object.

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

Выход :

 103

As we can see in the output, the Series.aggregate() function has successfully returned the sum of the underlying data of the given series object.
 
Example #2 : Use Series.aggregate() function to perform aggregation on the underlying data of the given series object.

# 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
Частота: A-DEC, dtype: int64

Now we will use Series.aggregate() function to find the maximum of all the values in the given series object.

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

Выход :

 84

As we can see in the output, the Series.aggregate() function has successfully returned the maximum of all the values in the given series object.

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.