簡體   English   中英

如何使用python排除一個組中的多個組?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM