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



我有一个数据帧:

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
]

最好的方法是什么?

使用GroupBy.transform获取与原始大小相同的Series的组计数,因此可以在boolean indexing:中通过Series.le<=进行过滤

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

如果性能不重要或数据帧可能较小,则使用DataFrameGroupBy.filter:

df =df.groupby(['type1','type2']).filter(lambda x: len(x) <= 2) 

最新更新