[英]Pandas group by and filter
我有以下 .csv
Name Location Product Type number
Greg 1 Fruit grape 1
Greg 1 Fruit apple 2
Greg 1 Bakery bread 5
Greg 1 Bakery roll 8
Greg 2 Fruit grape 7
Greg 2 Fruit apple 1
Greg 3 Fruit grape 2
Greg 4 Bakery roll 3
Greg 4 Bakery bread 4
Sam 5 Fruit apple 7
Sam 5 Fruit grape 9
Sam 5 Fruit apple 10
Sam 6 Bakery roll 11
Sam 6 Bakery bread 12
Sam 7 Fruit orange 13
Sam 7 Bakery roll 14
Tim 8 Fruit bread 16
Zack 9 Bakery roll 17
Zack 10 Fruit apple 19
Zack 10 Fruit grape 20
我想將其放入熊貓並按名稱分組,其中有多個位置有兩個以上產品的位置。 我仍然想保留產品的“編號”
以此類推,因為位置 1 的 Greg 有兩個產品
name location product type
Greg 1 Fruit, bakery grape,apple,bread,roll
我正在努力與 groupby 並最終將其恢復到我可以 .to_csv 的數據框
IIUC 使用具有nunique
transform
df1=df[df.groupby(['Name','Location']).Product.transform('nunique')>1]
Name Location Product Type number
0 Greg 1 Fruit grape 1
1 Greg 1 Fruit apple 2
2 Greg 1 Bakery bread 5
3 Greg 1 Bakery roll 8
14 Sam 7 Fruit orange 13
15 Sam 7 Bakery roll 14
如果您執行df.groupby([col_names])
,則 col_names 將成為索引。
為了將索引轉換回列,您需要使用DataFrame.reset_index()
方法。
希望有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.