简体   繁体   English

如何使用python排除一个组中的多个组?

[英]How to exclude more than one group in a groupby using python?

I have grouped the number of customers by region and year joined using groupby in Python.我使用 Python 中的 groupby 按地区和年份对加入的客户数量进行了分组。 However I want to remove several regions from the region group.但是我想从区域组中删除几个区域。

I know in order to exclude one group from a groupby you can use the following code:我知道为了从groupby排除一个组,您可以使用以下代码:

grouped = df.groupby(['Region'])
df1 = df.drop(grouped.get_group(('Southwest')).index).

Therefore I initially tried the following:因此,我最初尝试了以下方法:

grouped = df.groupby(['Region'])
df1 = df.drop(grouped.get_group(('Southwest','Northwest')).index)

However that gave me the apparent error ('Southwest','Northwest') .然而,这给了我明显的错误('Southwest','Northwest')

Now I am wondering if there is a way to drop several groups at once instead of me having to type out the above code repeatedly for each region I want to remove.现在我想知道是否有一种方法可以一次删除多个组,而不必为要删除的每个区域重复输入上述代码。

I expect the output of the final query to be similar to the image shown below however information regarding the Northwest and Southwest regions should be removed.我希望最终查询的输出类似于下面显示的图像,但是应该删除有关西北和西南地区的信息。 分组结果

It's not df1 = df.drop(grouped.get_group(('Southwest','Northwest')).index) .这不是df1 = df.drop(grouped.get_group(('Southwest','Northwest')).index) grouped.get_group takes a single name as argument. grouped.get_group以单个名称作为参数。 If you want to drop more than one group, you can use df1 = df.drop((grouped.get_group('Southwest').index, grouped.get_group('Northwest').index)) since drop can take a list as input.如果要删除多个组,可以使用df1 = df.drop((grouped.get_group('Southwest').index, grouped.get_group('Northwest').index))因为drop可以将列表作为输入。

As a side note, ('Southwest') evaluates to 'Southwest' (ie it's not a tuple).作为旁注, ('Southwest')评估为'Southwest' (即它不是元组)。 If you want to make a tuple of size 1, it's ('Southwest', )如果你想创建一个大小为 1 的元组,它是('Southwest', )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM