Search code examples
pythonpandas

Delete a group after pandas groupby


Is it possible to delete a group (by group name) from a groupby object in pandas? That is, after performing a groupby, delete a resulting group based on its name.


Solution

  • 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')]