我有一個數據框與多個列,我想使用數組後,這樣它應用於2列或更多列的組合。例如,假設我有兩列:使用熊貓數據框如何將計數應用於多級分組列?
user_id product_name
1 Apple
1 Banana
1 Apple
2 Carrot
2 Tomato
2 Carrot
2 Tomato
3 Milk
3 Cucumber
...
我想實現的是這樣的:
user_id product_name Product_Count_per_User
1 Apple 1
1 Banana 2
2 Carrot 2
2 Tomato 2
3 Milk 1
3 Cucumber 1
我無法得到它。我嘗試這樣做:
dcf6 = df3.groupby(['user_id','product_name'])['user_id', 'product_name'].count()
,但似乎並沒有得到我想要的東西,它會顯示4列,而不是3。如何做呢?謝謝。
嗯,計數用於非NaN計數,所以這裏更好的是大小。 – jezrael
@jezrael好的。但'groupby'默認情況下會拋出'nan'值,所以我想現在這種情況並不重要,因爲他正在計算組變量。但我同意'尺寸'是一個更好的選擇。 – Psidom