【问题标题】:pandas dataframe delete groups with more than n rows in groupby熊猫数据框删除 groupby 中超过 n 行的组
【发布时间】:2020-11-25 07:23:30
【问题描述】:

我有一个数据框:

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行或任意行可以删除,是否有任何基于要删除的条件?

标签: python pandas dataframe pandas-groupby


【解决方案1】:

使用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

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

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

【讨论】:

    猜你喜欢
    • 2017-05-18
    • 2020-05-11
    • 2015-06-13
    • 2016-10-09
    • 2013-12-19
    • 2021-04-30
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    相关资源
    最近更新 更多