user308827
user308827

Reputation: 21961

Discard group in pandas groupby operation

For the following dataframe (df), I am doing foll operation:

import pandas as pd
def fun(group):
    if(group.A.min() > 0.0):
        # discard the group
        return
    else:
        return group

df.groupby('cokey').apply(fun)

cokey       A   B
11168155    0   18
11168155    18  56
11168155    56  96
11168155    96  152
11168324    76  86
11168324    86  152

Is there a better way in pandas to discard a group during the groupby operation

Upvotes: 1

Views: 405

Answers (1)

EdChum
EdChum

Reputation: 393903

Just apply a filter:

In [7]:

df.groupby('cokey')[['A','B']].filter(lambda x: x['A'].min() > 50)
Out[7]:
    A    B
4  76   86
5  86  152

So in your case just do:

df.groupby('cokey')[['A','B']].filter(lambda x: x['A'].min() <= 0)

Upvotes: 1

Related Questions