在 pandas groupby 之后删除一个组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16910114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 20:52:20  来源:igfitidea点击:

Delete a group after pandas groupby

pythonpandas

提问by geomando

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.

是否可以从 Pandas 的 groupby 对象中删除一个组(按组名)?即在执行 groupby 后,根据其名称删除结果组。

回答by Dan Allan

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

已经讨论了按组过滤 DataFrame 。Pandas 的未来版本可能包含更方便的方法

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

但目前,我认为这是grouped按名称过滤 GroupBy 对象并返回剩余组的 DataFrame的最简洁方法。

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

回答by waitingkuo

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

似乎没有直接的方法可以从 groupby 对象中删除组。我认为你可以在 groupby by 之前过滤掉那些 groupby

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

回答by FinnHolms?

Should be easy:

应该很容易:

df.drop(index='group_name',inplace=True)

df.drop(index='group_name',inplace=True)