pandas dataframe删除groupby中超过n行的组

oku*_*oub 3 python dataframe pandas 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       c        m       2    1     8
       a       b        h       8    6     3
       a       b        e       4    2     7]
Run Code Online (Sandbox Code Playgroud)

我想根据列 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
  ]
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么?

jez*_*ael 5

用于获取与原始大小相同的GroupBy.transform组数,因此可以通过for in进行过滤:SeriesSeries.le<=boolean indexing

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
Run Code Online (Sandbox Code Playgroud)

如果性能不重要或者可以使用小型 DataFrame DataFrameGroupBy.filter

df =df.groupby(['type1','type2']).filter(lambda x: len(x) <= 2) 
Run Code Online (Sandbox Code Playgroud)