pandas 分组过滤 [英] Pandas GroupBy Filtering

查看:58
本文介绍了 pandas 分组过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking to understand how to filter a groupby object.

我正在通过以下方式生成此信息:

I am generating this through:

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但没有产品类型Z的订单

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

In the example above, only order 1 is legitimate. Order 2 and 3 would be filtered out.

推荐答案

filter接受可返回布尔值的可调用对象.该可调用对象将使用整个组数据框.如果布尔值为True,则数据帧返回.如果False,则什么也不会回来.

filter takes a callable that returns a boolean. That callable will take the entire groups dataframe. If the boolean is True, the dataframe comes back. If False then nothing comes back.

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)

这篇关于 pandas 分组过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆