gpt4 book ai didi

python - apply() 和 aggregate() 函数之间的 Pandas 区别

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:17 25 4
gpt4 key购买 nike

如果我只是传递一个像

这样的函数,DataFrame.aggregate() 和DataFrame.apply() 函数之间的返回值(类型)有什么不同吗?
func=lambda x: x**2

因为返回值看起来是一样的。而文档只告诉:

apply() --> applied : Series or DataFrame

aggregate() --> aggregated : DataFrame

最佳答案

agg(aggregate 的缩写)和 apply 有两个版本:第一个是在 groupby 对象上定义的,第二个是在 DataFrame 上定义的。

如果您考虑 groupby.agggroupby.apply,主要区别在于应用是灵活的 (docs):

Some operations on the grouped data might not fit into either the aggregate or transform categories. Or, you may simply want GroupBy to infer how to combine the results. For these, use the apply function, which can be substituted for both aggregate and transform in many standard use cases.

Note: apply can act as a reducer, transformer, or filter function, depending on exactly what is passed to apply. So depending on the path taken, and exactly what you are grouping. Thus the grouped columns(s) may be included in the output as well as set the indices.

参见 Python Pandas : How to return grouped lists in a column as a dict例如,为了说明如何自动更改返回类型。

另一方面,

groupby.agg 非常适合应用 cython 优化函数(即能够计算 'sum''mean' , 'std' 等非常快)。它还允许在不同的列上计算多个(不同的)函数。例如,

df.groupby('some_column').agg({'first_column': ['mean', 'std'],
'second_column': ['sum', 'sem']}

计算第一列的平均值和标准差,以及第二列平均值的总和和标准误差。参见 dplyr summarize equivalent in pandas有关更多示例。

What is the difference between pandas agg and apply function? 中也总结了这些差异但那篇着重于 groupby.agggroupby.apply 之间的区别。

DataFrame.agg 是 0.20 版中的新内容。早些时候,我们无法将多个不同的函数应用于不同的列,因为它只能用于 groupby 对象。现在,您可以通过在其列上计算多个不同的函数来汇总 DataFrame。来自 Is there a pandas equivalent of dplyr::summarise? 的示例:

iris.agg({'sepal_width': 'min', 'petal_width': 'max'})

petal_width 2.5
sepal_width 2.0
dtype: float64

iris.agg({'sepal_width': ['min', 'median'], 'sepal_length': ['min', 'mean']})

sepal_length sepal_width
mean 5.843333 NaN
median NaN 3.0
min 4.300000 2.0

这对于 DataFrame.apply 是不可能的。它要么逐列进行,要么逐行进行,并在该列/行上执行相同的功能。对于像 lambda x: x**2 这样的单个函数,它们产生相同的结果,但它们的预期用途却大不相同。

关于python - apply() 和 aggregate() 函数之间的 Pandas 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44864655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com