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.
In the pandas series constructor, there is a method called drop() which is used to remove specified rows from the pandas series object. It won't update the original series object with deleted rows instead of updating the original series object, it will return another series object with the removed rows.
Groupby preserves the order of rows within each group. When calling apply, add group keys to index to identify pieces. Reduce the dimensionality of the return type if possible, otherwise return a consistent type.
What is the GroupBy function? Pandas' GroupBy is a powerful and versatile function in Python. It allows you to split your data into separate groups to perform computations for better analysis.
Groupby preserves the order of rows within each group. Thus, it is clear the "Groupby" does preserve the order of rows within each group.
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]
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')]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With