Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete a group after pandas groupby

Tags:

python

pandas

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.

like image 282
geomando Avatar asked Jun 04 '13 05:06

geomando


People also ask

How do I delete a pandas group?

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.

Does Groupby maintain order pandas?

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 does Group_by do in pandas?

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.

Can I change my order on Groupby?

Groupby preserves the order of rows within each group. Thus, it is clear the "Groupby" does preserve the order of rows within each group.


3 Answers

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]
like image 22
waitingkuo Avatar answered Oct 13 '22 20:10

waitingkuo


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')]
like image 123
Dan Allan Avatar answered Oct 13 '22 20:10

Dan Allan


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.

like image 2
Ahmad Asmndr Avatar answered Oct 13 '22 19:10

Ahmad Asmndr