agg() 方法在 Pandas 系列中有什么作用?

agg()pandas Series 中的方法用于在一个系列对象上应用一个或多个函数。通过使用这种agg()方法,我们可以一次对一个系列应用多个函数。

要一次使用多个函数,我们需要将这些函数名称作为元素列表发送给agg()函数。

示例

# import pandas package
import pandas as pd

# create a pandas series
s = pd.Series([1,2,3,4,5,6,7,8,9,10])
print(s)

# Applying agg function
result = s.agg([max, min, len])
print('Output of agg method',result)

解释

对象“s”有10个整数元素,通过使用该agg()方法我们对这个系列对象“s”应用了一些聚合操作。聚合操作是 min、max 和 len。

输出结果

0   1
1   2
2   3
3   4
4   5
5   6
6   7
7   8
8   9
9  10
dtype: int64

Output of agg method
max  10
min   1
len  10
dtype: int64

在以下示例中,pandas 系列agg()方法将返回一个包含列表中每个函数的结果的系列。因此输出将类似于,函数名称后跟结果输出值。

示例

# import pandas package
import pandas as pd

# create a pandas series
s = pd.Series([1,2,3,4,5,6,7,8,9,10])
print(s)

# Applying agg function
result = s.agg(mul)
print('Output of agg method',result)

解释

让我们再举一个例子,并使用 方法将单个函数应用于系列对象agg()。这里我们将 mul 函数名作为参数应用到agg()函数中。

输出结果

0   1
1   2
2   3
3   4
4   5
5   6
6   7
7   8
8   9
9  10
dtype: int64

Output of agg method
0   2
1   4
2   6
3   8
4  10
5  12
6  14
7  16
8  18
9  20
dtype: int64

该arr()方法的输出与实际的系列对象“s”一起显示在上面的块中。此 mul 函数应用于系列元素,结果输出作为该agg()方法的另一个系列对象返回。