Delete a group after pandas groupby

it is so simple, you need to use the filter function and lambda exp:

df_filterd=df.groupby('name').filter(lambda x:(x.name == 'cond1' or...(other condtions )))

you need to take care that if you want to use more than condtion to put it in brackets().. and you will get back a DataFrame not GroupObject.


Filtering a DataFrame groupwise has been discussed. And a future release of pandas may include a more convenient way to do it.

But currently, here is what I believe to be the most succinct way to filter the GroupBy object grouped by name and return a DataFrame of the remaining groups.

df.drop(grouped.get_group(group_name).index)

And here is a more general method derived from the links above:

df[grouped[0].transform(lambda x: x.name != group_name).astype('bool')]

Seems there's no direct way to delete a group from a groupby object. I think you can filter out those groupby before groupby by

df = df[df[group] != group_name]

Tags:

Python

Pandas