【问题标题】:How to apply multiple functions to a groupby object如何将多个函数应用于 groupby 对象
【发布时间】:2017-11-04 01:06:58
【问题描述】:

例如,我有两个 lambda 函数可应用于分组数据框:

df.groupby(['A', 'B']).apply(lambda g: ...)
df.groupby(['A', 'B']).apply(lambda g: ...)

两者都可以,但结合起来就不行了:

df.groupby(['A', 'B']).apply([lambda g: ..., lambda g: ...])

这是为什么呢?如何将不同的函数应用于分组对象并将每个结果逐列连接在一起?

有没有办法不为函数指定某些列?您所建议的一切似乎只适用于某些列。

【问题讨论】:

  • 相关且可能的骗子:stackoverflow.com/questions/14529838/…,这是你所追求的吗?
  • 查看 agg 函数。 df.groupby(['field1']).agg({'field2':'mean','field3':'count'})
  • 我不需要对不同的列应用不同的函数。我希望将这两个函数应用于整个分组数据框。我错过了什么吗?
  • groups = df.groupby(...); result = groups.apply(...).join(groups.apply(...))

标签: python pandas dataframe


【解决方案1】:

这是一个突出pandas 0.20的变化之一的好机会

Deprecate groupby.agg() with a dictionary when renaming

这是什么意思?
考虑数据框df

df = pd.DataFrame(dict(
        A=np.tile([1, 2], 2).repeat(2),
        B=np.repeat([1, 2], 2).repeat(2),
        C=np.arange(8)
    ))
df

   A  B  C
0  1  1  0
1  1  1  1
2  2  1  2
3  2  1  3
4  1  2  4
5  1  2  5
6  2  2  6
7  2  2  7

我们以前可以这样做

df.groupby(['A', 'B']).C.agg(dict(f1=lambda x: x.size, f2=lambda x: x.max()))

     f1  f2
A B        
1 1   2   1
  2   2   5
2 1   2   3
  2   2   7

我们的名字'f1''f2' 被放置为列标题。但是,使用 pandas 0.20 我得到了这个

//anaconda/envs/3.6/lib/python3.6/site-packages/ipykernel/__main__.py:1: FutureWarning: using a dict on a Series for aggregation
is deprecated and will be removed in a future version
  if __name__ == '__main__':

那是什么意思?如果我在没有命名字典的情况下做两个lambdas 怎么办?

df.groupby(['A', 'B']).C.agg([lambda x: x.size, lambda x: x.max()])

---------------------------------------------------------------------------
SpecificationError                        Traceback (most recent call last)
<ipython-input-398-fc26cf466812> in <module>()
----> 1 print(df.groupby(['A', 'B']).C.agg([lambda x: x.size, lambda x: x.max()]))

//anaconda/envs/3.6/lib/python3.6/site-packages/pandas/core/groupby.py in aggregate(self, func_or_funcs, *args, **kwargs)
   2798         if hasattr(func_or_funcs, '__iter__'):
   2799             ret = self._aggregate_multiple_funcs(func_or_funcs,
-> 2800                                                  (_level or 0) + 1)
   2801         else:
   2802             cyfunc = self._is_cython_func(func_or_funcs)

//anaconda/envs/3.6/lib/python3.6/site-packages/pandas/core/groupby.py in _aggregate_multiple_funcs(self, arg, _level)
   2863             if name in results:
   2864                 raise SpecificationError('Function names must be unique, '
-> 2865                                          'found multiple named %s' % name)
   2866 
   2867             # reset the cache so that we

SpecificationError: Function names must be unique, found multiple named <lambda>

名为 '&lt;lambda&gt;' 的多个列上的 pandas 错误

解决方案:命名你的函数

def f1(x):
    return x.size

def f2(x):
    return x.max()

df.groupby(['A', 'B']).C.agg([f1, f2])

     f1  f2
A B        
1 1   2   1
  2   2   5
2 1   2   3
  2   2   7

【讨论】:

  • 很棒的输入!但是当我明确命名每个函数时,我得到了多个错误。喜欢TypeError: an integer is requiredKeyError: 'o'。我不知道为什么会这样。
【解决方案2】:

你为什么不使用 agg ?

df.groupby(['A', 'B']).agg(lambda g: ...)

可能是您发布问题后的新行为

【讨论】:

    猜你喜欢
    • 2013-04-23
    • 2013-01-09
    • 2020-05-14
    • 2023-01-23
    • 1970-01-01
    相关资源
    最近更新 更多