Pandas Series 中的 agg() 方法起什么作用?

pandasserver side programmingprogramming更新于 2025/9/28 11:07:17

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

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

示例

# 导入 pandas 包
import pandas as pd

# 创建一个 pandas 系列
s = pd.Series([1,2,3,4,5,6,7,8,9,10])
print(s)

# 应用 agg 函数
result = s.agg([max, min, len])
print('agg 方法的输出',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() 方法将返回一个包含列表中每个函数结果的系列。因此,输出将类似于函数名称后跟最终输出值。

示例

# 导入 pandas 包
import pandas as pd

# 创建一个 Pandas 系列
s = pd.Series([1,2,3,4,5,6,7,8,9,10])
print(s)

# 应用 agg 函数
result = s.agg(mul)
print('agg 方法的输出',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() 方法返回。


相关文章