56

我无法弄清楚 Pandas.aggregate.apply函数之间的区别。
以下面的例子为例:我加载一个数据集,做一个groupby,定义一个简单的函数,或者用户.agg或者.apply.

如您所见,我的函数中的打印语句在使用.aggand后会产生相同的输出.apply。结果,另一方面是不同的。这是为什么?

import pandas
import pandas as pd
iris = pd.read_csv('iris.csv')
by_species = iris.groupby('Species')
def f(x):
    ...:     print type(x)
    ...:     print x.head(3)
    ...:     return 1

使用apply

by_species.apply(f)
#<class 'pandas.core.frame.DataFrame'>
#   Sepal.Length  Sepal.Width  Petal.Length  Petal.Width Species
#0           5.1          3.5           1.4          0.2  setosa
#1           4.9          3.0           1.4          0.2  setosa
#2           4.7          3.2           1.3          0.2  setosa
#<class 'pandas.core.frame.DataFrame'>
#   Sepal.Length  Sepal.Width  Petal.Length  Petal.Width Species
#0           5.1          3.5           1.4          0.2  setosa
#1           4.9          3.0           1.4          0.2  setosa
#2           4.7          3.2           1.3          0.2  setosa
#<class 'pandas.core.frame.DataFrame'>
#    Sepal.Length  Sepal.Width  Petal.Length  Petal.Width     Species
#50           7.0          3.2           4.7          1.4  versicolor
#51           6.4          3.2           4.5          1.5  versicolor
#52           6.9          3.1           4.9          1.5  versicolor
#<class 'pandas.core.frame.DataFrame'>
#     Sepal.Length  Sepal.Width  Petal.Length  Petal.Width    Species
#100           6.3          3.3           6.0          2.5  virginica
#101           5.8          2.7           5.1          1.9  virginica
#102           7.1          3.0           5.9          2.1  virginica
#Out[33]: 
#Species
#setosa        1
#versicolor    1
#virginica     1
#dtype: int64

使用agg

by_species.agg(f)
#<class 'pandas.core.frame.DataFrame'>
#   Sepal.Length  Sepal.Width  Petal.Length  Petal.Width Species
#0           5.1          3.5           1.4          0.2  setosa
#1           4.9          3.0           1.4          0.2  setosa
#2           4.7          3.2           1.3          0.2  setosa
#<class 'pandas.core.frame.DataFrame'>
#    Sepal.Length  Sepal.Width  Petal.Length  Petal.Width     Species
#50           7.0          3.2           4.7          1.4  versicolor
#51           6.4          3.2           4.5          1.5  versicolor
#52           6.9          3.1           4.9          1.5  versicolor
#<class 'pandas.core.frame.DataFrame'>
#     Sepal.Length  Sepal.Width  Petal.Length  Petal.Width    Species
#100           6.3          3.3           6.0          2.5  virginica
#101           5.8          2.7           5.1          1.9  virginica
#102           7.1          3.0           5.9          2.1  virginica
#Out[34]: 
#           Sepal.Length  Sepal.Width  Petal.Length  Petal.Width
#Species                                                         
#setosa                 1            1             1            1
#versicolor             1            1             1            1
#virginica              1            1             1            1
4

4 回答 4

53

apply将该函数应用于每个组(您的Species)。您的函数返回 1,因此您最终会为 3 个组中的每一个提供 1 个值。

agg聚合每个组的每一列(特征),因此最终每组每列都有一个值。

请阅读groupby文档,它们非常有帮助。网上也有很多教程。

于 2014-02-17T14:26:24.337 回答
33

注意:这些比较与 DataframeGroupby 对象相关

与,对于 DataFrame GroupBy 对象相比,使用的一些可能的优点.agg()是:.apply()

  1. .agg()提供一次应用多个函数的灵活性,或者将函数列表传递给每一列。

  2. 此外,一次将不同的函数应用于数据框的不同列。

这意味着您几乎可以控制每个操作的每一列。

以下是更多详细信息的链接:http: //pandas.pydata.org/pandas-docs/version/0.13.1/groupby.html


但是,该apply函数可能仅限于一次将一个函数应用于数据帧的每一列。因此,您可能必须重复调用 apply 函数才能对同一列调用不同的操作。

以下是.apply().agg()DataframeGroupBy 对象的一些示例比较:

给定以下数据框:

In [261]: df = pd.DataFrame({"name":["Foo", "Baar", "Foo", "Baar"], "score_1":[5,10,15,10], "score_2" :[10,15,10,25], "score_3" : [10,20,30,40]})

In [262]: df
Out[262]: 
   name  score_1  score_2  score_3
0   Foo        5       10       10
1  Baar       10       15       20
2   Foo       15       10       30
3  Baar       10       25       40

让我们先看看使用的操作.apply()

In [263]: df.groupby(["name", "score_1"])["score_2"].apply(lambda x : x.sum())
Out[263]: 
name  score_1
Baar  10         40
Foo   5          10
      15         10
Name: score_2, dtype: int64

In [264]: df.groupby(["name", "score_1"])["score_2"].apply(lambda x : x.min())
Out[264]: 
name  score_1
Baar  10         15
Foo   5          10
      15         10
Name: score_2, dtype: int64

In [265]: df.groupby(["name", "score_1"])["score_2"].apply(lambda x : x.mean())
Out[265]: 
name  score_1
Baar  10         20.0
Foo   5          10.0
      15         10.0
Name: score_2, dtype: float64

现在,毫不费力地使用 .agg()查看相同的操作:

In [276]: df.groupby(["name", "score_1"]).agg({"score_3" :[np.sum, np.min, np.mean, np.max], "score_2":lambda x : x.mean()})
Out[276]: 
              score_2 score_3               
             <lambda>     sum amin mean amax
name score_1                                
Baar 10            20      60   20   30   40
Foo  5             10      10   10   10   10
     15            10      30   30   30   30

因此,.agg().apply(). 但是,如果您只处理纯数据框对象而不是 DataFrameGroupBy 对象,那么apply()它可能非常有用,因为apply()可以沿数据框的任何轴应用函数。

(例如:axis = 0意味着按列操作.apply(),是默认模式,并且axis = 1在处理纯数据帧对象时意味着按行操作)。

于 2016-05-03T05:18:57.520 回答
2

应用和聚合之间的主要区别是:

apply()- 
    cannot be applied to multiple groups together 
    For apply() - We have to get_group()
    ERROR : -iris.groupby('Species').apply({'Sepal.Length':['min','max'],'Sepal.Width':['mean','min']})# It will throw error
    Work Fine:-iris.groupby('Species').get_group('Setosa').apply({'Sepal.Length':['min','max'],'Sepal.Width':['mean','min']})# It will throw error
        #because functions are applied to one data frame

agg()- 
    can be applied to multiple groups together
    For apply() - We do not have to get_group() 
    iris.groupby('Species').agg({'Sepal.Length':['min','max'],'Sepal.Width':['mean','min']})
    iris.groupby('Species').get_group('versicolor').agg({'Sepal.Length':['min','max'],'Sepal.Width':['mean','min']})        
于 2019-10-26T10:32:15.153 回答
0

当使用 apply 到我遇到的 groupby 时,.apply它将返回分组的列。文档中有一条注释(pandas.pydata.org/pandas-docs/stable/groupby.html):

“...因此,分组的列可以包含在输出中并设置索引。”

.aggregate不会返回分组的列。

于 2018-08-17T15:59:33.790 回答