Pandas 序列aggregate()方法

原文:https://www.studytonight.com/pandas/pandas-series-aggregate-method

在本教程中,我们将讨论和学习 PandasSeries.aggregate()方法。此方法使用沿指定轴的一个或多个操作来聚合系列元素。当单个方法调用该方法时,它返回一个标量值,当多个方法或方法列表调用该方法时,它返回多个输出。

下面是Series.aggregate()方法的语法。

句法

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

因素

func: 表示方法、字符串、列表或字典。它是用于聚合数据的方法。

轴:如果为 0 或“索引”,则对每列应用一种方法。如果为 1 或“列”,则对每行应用一个方法。默认轴值为 0 或“索引”。

*args: 表示传递给 func 的位置参数。

**kwargs: 表示传递给 func 的关键字参数。

例:PandasSeries.aggregate()方法

让我们使用Series.aggregate() 方法聚合系列元素。这里,在这个例子中,我们通过将single method传递给Series.aggregate() 方法来聚合Series的元素。见下面的例子。

我们使用'sum''min''max''mean''count'方法进行聚合。

#importing pandas as pd
import pandas as pd
#creating Series
s= pd.Series([2,3,4])
print("------After aggregating the result is------")
print("The sum of the series elements is:",s.aggregate('sum'))
print("The min of the series elements is:",s.aggregate('min'))
print("The max of the series elements is:",s.aggregate('max'))
print("The mean of the series elements is:",s.aggregate('mean'))
print("The count of the series elements is:",s.aggregate('count'))

-合计后的结果为- 系列元素之和为:9 系列元素的最小值为:2 系列元素的最大值为:4 系列元素的平均值为:3.0 系列元素的个数为:3

例 2:PandasSeries.aggregate()方法

让我们使用Series.aggregate() 方法聚合系列元素。这里,在这个例子中,我们通过将list of methods 传递给Series.agg() 方法来聚合Series的元素。

我们将'sum''min''max' 方法传递给列表,Series.aggregate() 方法返回多个输出。见下面的例子。

#importing pandas as pd
import pandas as pd
#creating Series
s= pd.Series([2,3,4])
print("The ouput of the agg method is:\n",s.aggregate(['sum','min','max']))

agg 方法的输出为: sum 9 min 2 max 4 数据类型:int64

例 3:PandasSeries.aggregate()方法

我们可以使用user-defined 方法聚合系列元素。创建一个用户定义的方法,在这个例子中,我们创建了add() 方法,该方法向 Series 的元素添加值 1 ,如果元素大于 3,则返回相同的元素。见下面的例子。

#importing pandas as pd
import pandas as pd
#defining a user-defined function
def add(x):
    if x>3:
        return x+1
    else:
        return x
#creating Series
s= pd.Series([3,7,5,2,9,4,2])
print("------After aggregating the result is------")
print(s.aggregate(add))

-汇总后的结果为- 0 3 1 8 2 6 3 2 4 10 5 6 2 数据类型:int64

结论

在本教程中,我们学习了 PandasDataFrame.aggregate()方法。我们学习了语法、参数,并通过将此方法应用于系列来解决示例。