熊猫数据框删除groupby中具有多于n行的组

时间:2020-08-05 06:39:40

标签: 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       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
  ]

这样做的最好方法是什么?

1 个答案:

答案 0 :(得分:4)

使用GroupBy.transform获取与原始大小相同的Alpha alpha = new Alpha(); Beta beta = new Beta(); Random rs = new Random(); // Alpha has a method Push() and Beta has a method Colour() alpha.Push(beta.Colour(rs)); 的组计数,因此可以在Series.le中用boolean indexing过滤Series

<=

如果性能并不重要或可能使用较小的DataFrame,请使用DataFrameGroupBy.filter

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