如何在过滤操作后保留Pandas.GroupBy对象

时间:2016-03-16 22:13:28

标签: python pandas group-by

我希望对数据框中的组进行操作,但仅限于过滤后的组。在我看来,我必须分组,然后filter,然后再组合,最后进行我的操作。有没有办法绕过第二次分组操作?如果我真的想要保留作为GroupBy对象的上下文,那似乎很浪费。

df2 = df1.groupby('ColumnX').filter( lambda x: len(x) >= 2 ).groupby('ColumnX').mean()

有没有办法进行组过滤器,其返回值不是数据帧而是GroupBy对象?

这里有一些玩具数据用于演示......

>>> df = pandas.DataFrame({ 'ColumnX' : ['a', 'a', 'a' , 'b' , 'b' , 'c' ] , 'ColumnY' : [ 1 , 2  ,  3  ,  1  , 2  ,  99 ] })
>>> df
  ColumnX  ColumnY
0       a        1
1       a        2
2       a        3
3       b        1
4       b        2
5       c       99
>>> df.groupby('ColumnX')
<pandas.core.groupby.DataFrameGroupBy object at 0x0000000005974438>
>>> df.groupby('ColumnX').filter( lambda x : len(x) >=2 )
  ColumnX  ColumnY
0       a        1
1       a        2
2       a        3
3       b        1
4       b        2
>>> df.groupby('ColumnX').filter( lambda x : len(x) >=2 ).groupby('ColumnX')
<pandas.core.groupby.DataFrameGroupBy object at 0x00000000033A1588>
>>> df.groupby('ColumnX').filter( lambda x : len(x) >=2 ).groupby('ColumnX').mean()
         ColumnY
ColumnX
a            2.0
b            1.5
>>>

0 个答案:

没有答案