[英]How to group data by more than one column with groupby - if possible
[英]How to exclude more than one group in a groupby using python?
我使用 Python 中的 groupby 按地区和年份对加入的客户数量进行了分组。 但是我想从区域组中删除几个区域。
我知道为了从groupby
排除一个组,您可以使用以下代码:
grouped = df.groupby(['Region'])
df1 = df.drop(grouped.get_group(('Southwest')).index).
因此,我最初尝试了以下方法:
grouped = df.groupby(['Region'])
df1 = df.drop(grouped.get_group(('Southwest','Northwest')).index)
然而,这给了我明显的错误('Southwest','Northwest')
。
现在我想知道是否有一种方法可以一次删除多个组,而不必为要删除的每个区域重复输入上述代码。
这不是df1 = df.drop(grouped.get_group(('Southwest','Northwest')).index)
。 grouped.get_group
以单个名称作为参数。 如果要删除多个组,可以使用df1 = df.drop((grouped.get_group('Southwest').index, grouped.get_group('Northwest').index))
因为drop
可以将列表作为输入。
作为旁注, ('Southwest')
评估为'Southwest'
(即它不是元组)。 如果你想创建一个大小为 1 的元组,它是('Southwest', )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.