Python 数据帧删除groupby中超过n行的组

Python 数据帧删除groupby中超过n行的组,python,pandas,dataframe,pandas-groupby,Python,Pandas,Dataframe,Pandas Groupby,我有一个数据帧: df = [type1 , type2 , type3 , val1, val2, val3 a b q 1 2 3 a c w 3 5 2 b c t 2 9 0 a b p 4 6 7 a

我有一个数据帧:

df = [type1 , type2 , type3 , val1, val2, val3
       a       b        q       1    2     3
       a       c        w       3    5     2
       b       c        t       2    9     0
       a       b        p       4    6     7
       a       c        m       2    1     8
       a       b        h       8    6     3
       a       b        e       4    2     7]
我想基于列type1、type2应用groupby,并从数据框中删除超过2行的组。因此,新的数据帧将是:

df = [type1 , type2 , type3 , val1, val2, val3
       a       c        w       3    5     2
       b       c        t       2    9     0
       a       c        m       2    1     8
  ]

最好的方法是什么?

用于获取与原始大小相同的
系列
的组计数,因此可能的过滤方式为
如果有超过2行或任何任意行可以删除,是否有任何条件基于您要删除的内容?
df = df[df.groupby(['type1','type2'])['type1'].transform('size').le(2)]
print (df)
  type1 type2 type3  val1  val2  val3
1     a     c     w     3     5     2
2     b     c     t     2     9     0
4     a     c     m     2     1     8
df =df.groupby(['type1','type2']).filter(lambda x: len(x) <= 2)