Pandas GroupBy Filtering

前端 未结 1 451
感动是毒
感动是毒 2021-01-24 07:25

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

I am generating this through:

groupby = df.groupby([\'Order #\', \'ProductLine\', \'Product         


        
相关标签:
1条回答
  • 2021-01-24 07:55

    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.

    Only A

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

    A and not Z

    def f(df):
        v = df.ProductLine.values
        return ('A' in v) and ('Z' not in v)
    
    df.groupby(['Order #', 'ProductLine', 'ProductType']).filter(f)
    
    0 讨论(0)
提交回复
热议问题