[英]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.