Pandas Series 聚合方法

PythonPythonBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,我们将学习 Pandas Series 对象中的 agg() 方法。agg() 方法允许我们沿指定轴对一个 Series 的元素应用一个或多个聚合函数。当使用单个函数调用时,它返回一个标量值;当使用多个函数调用时,它返回多个值。

虚拟机提示

虚拟机启动完成后,点击左上角切换到 Notebook 选项卡以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟,直到 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时可以询问 Labby。请在实验结束后提供反馈,我们将及时为你解决问题。

导入必要的库

首先,我们需要导入 pandas 库,它用于数据操作和分析。

import pandas as pd

创建一个 Series

接下来,我们将使用一些示例数据创建一个 Series 对象。

s = pd.Series([2, 3, 4])

使用单个函数进行聚合

现在,让我们使用单个函数对 Series 的元素进行聚合。我们将以 sum()min()max()mean()count() 函数为例。

print("The sum of the series elements is:", s.agg('sum'))
print("The min of the series elements is:", s.agg('min'))
print("The max of the series elements is:", s.agg('max'))
print("The mean of the series elements is:", s.agg('mean'))
print("The count of the series elements is:", s.agg('count'))

使用多个函数进行聚合

我们还可以使用多个函数对 Series 的元素进行聚合。这里,我们将一个函数列表传递给 agg() 方法。

print("The output of the agg method is:\n", s.agg(['sum', 'min', 'max']))

使用用户自定义函数进行聚合

最后,我们可以使用用户自定义函数对元素进行聚合。在这个例子中,我们将创建一个名为 add() 的函数,该函数会对大于 3 的元素加 1,否则返回原值。

def add(x):
    if x > 3:
        return x + 1
    else:
        return x

print("After aggregating the result is:\n", s.agg(add))

总结

在本实验中,我们学习了如何在 Pandas Series 对象中使用 agg() 方法。我们了解了如何使用内置函数、多个函数以及用户自定义函数对元素进行聚合。agg() 方法是汇总和分析 Series 数据的一个强大工具。