[英]How can I do Python for groupby in dataframe
我有一個 dataframe,其中包含交易。 我想對數據進行分組。
buy_date category subcategory product actual_price sell_price
1/1/2021 Cloth women shirt style A 5 4
1/1/2021 Cloth men skirt style A 7 6.5
1/1/2021 Accessories ear sky wing 2 1
2/1/2021 Automotive wheel small 21 18
2/1/2021 Automotive wheel big 34 30
1/14/2021 Accessories ring queen couple 3 3
1/17/2021 Cloth women shirt style B 7 7
1/17/2021 Cloth men skirt style A 7 6.5
4/2/2021 Cloth men skirt style A 10 9
5/2/2021 Accessories ring queen couple 3 2.5
7/2/2021 Cloth women shirt style B 16 12
7/2/2021 Automotive wheel big 40 35
2/26/2021 Accessories ring queen couple 4 4
2/26/2021 Cloth women shirt style B 9 5
2/26/2021 Cloth men skirt style A 7 9
2/28/2021 Accessories ear sky wing 2 1
1/3/2021 Automotive wheel big 38 35
1/3/2021 Accessories ring queen couple 4 4
7/3/2021 Automotive wheel big 39 37
3/31/2021 Accessories ring queen couple 4 4
我想獲得每個類別和子類別的平均每月銷售量和實際價格。 我嘗試了很多方法,但它們都無法正常工作。 謝謝
做就是了:
>>> df.groupby(['category', 'subcategory']).mean()
actual_price sell_price
category subcategory
Accessories ear 2.00 1.00
ring 3.60 3.50
Automotive wheel 34.40 31.00
Cloth men 7.75 7.75
women 9.25 7.00
>>>
您可以找到month
,然后使用三個所需的列進行groupby
。
嘗試這個:
df['month'] = pd.to_datetime(df["buyDate"]).dt.month
df.groupby(['month','category', 'subcategory']).mean()
將Grouper
與聚合mean
一起使用:
df['buyDate'] = pd.to_datetime(df["buyDate"])
df.groupby([pd.Grouper(freq='M', key='buyDate'),'category', 'subcategory']).mean()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.