如何将多个函数应用于groupby对象

时间:2017-06-02 15:02:45

标签: python pandas dataframe

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

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

两者都可以,但不能合并:

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

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

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

2 个答案:

答案 0 :(得分:4)

这是一个很好的机会来突出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>

名为'<lambda>'

的多列上的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

答案 1 :(得分:0)

为什么不使用agg?

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

自您发布问题以来,这可能是一种新行为

相关问题