【问题标题】:Pandas GroupBy FilteringPandas Group按过滤
【发布时间】:2017-04-20 04:58:21
【问题描述】:

我希望了解如何过滤 groupby 对象。

我通过以下方式生成:

groupby = df.groupby(['Order #', 'ProductLine', 'ProductType']).size()

结果是:

Order #     ProductLine     ProductType       QTY
  1              A              Z              1
                                Y              1
                 B              X              2
  2              A              Z              1
                                Y              1
  3              A              Y              1
                 B              X              1

我需要过滤掉两个条件:

  1. 仅包含产品 A 的订单
  2. 包含产品 A 但没有 ProductType Z 的订单

在上面的示例中,只有订单 1 是合法的。订单 2 和 3 将被过滤掉。

【问题讨论】:

    标签: pandas


    【解决方案1】:

    filter 接受一个返回布尔值的可调用对象。该可调用对象将采用整个组数据框。如果布尔值是True,则数据框会返回。如果False 则不会返回任何内容。

    仅限A

    def f(df):
        v = df.ProductLine.values
        return (v == 'A').all()
    
    df.groupby(['Order #', 'ProductLine', 'ProductType']).filter(f)
    

    A 而不是Z

    def f(df):
        v = df.ProductLine.values
        return ('A' in v) and ('Z' not in v)
    
    df.groupby(['Order #', 'ProductLine', 'ProductType']).filter(f)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-18
      • 2016-08-21
      • 2018-12-27
      • 2017-09-06
      • 1970-01-01
      相关资源
      最近更新 更多