gpt4 book ai didi

python - 数据透视表和按月分组

转载 作者:行者123 更新时间:2023-12-05 03:26:45 28 4
gpt4 key购买 nike

我有一个 DataFrame df 如下:

df = pd.DataFrame([["12", "10-01-2022", 'boot', "shoe", 100, 50],
["211", "10-01-2022", 'sandal', "shoe", 210, 20],
["321", "10-02-2022", 'boot', "shoe", 100, 45],
["413", "10-02-2022", 'boot', "shoe", 100, 45],
["15", "10-02-2022", 'dress', "cloth", 155, 95],
["633", "10-03-2022", 'boot', "shoe", 75, 30],
["247", "10-03-2022", 'boot', "shoe", 75, 30],
["8787", "10-04-2022", 'boot', "shoe", 120, 45],
["9232", "10-05-2022", 'shirt', "cloth", 75, 30],
["12340", "10-05-2022", 'dress', "cloth", 175, 95 ]],
columns=["count", "date", "name", "category", "price", "revenue"])

我需要按月汇总以查看数量、价格和收入的总和,如下所示:

|name  | category |Count                        | price                       | revenue            |      
| | | Jan | Feb | Mar | Apr | Mai | Jan | Feb | Mar | Apr | Mai |Jan | Feb | Mar | Apr | Mai |
|boot | shoe | 12 | 734 | 880 | 8787| - | 100 | 100 | 75 | 120 | - | 50 | 45 | 30 | 45 |-|
|sandal| shoe | 211 | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
|dress | cloth | - | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
|shirt | cloth | - | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |

我该怎么做?

最佳答案

试试这个:

df = pd.DataFrame([["12", "10-01-2022", 'boot', "shoe", 100, 50],
["211", "10-01-2022", 'sandal', "shoe", 210, 20],
["321", "10-02-2022", 'boot', "shoe", 100, 45],
["413", "10-02-2022", 'boot', "shoe", 100, 45],
["15", "10-02-2022", 'dress', "cloth", 155, 95],
["633", "10-03-2022", 'boot', "shoe", 75, 30],
["247", "10-03-2022", 'boot', "shoe", 75, 30],
["8787", "10-04-2022", 'boot', "shoe", 120, 45],
["9232", "10-05-2022", 'shirt', "cloth", 75, 30],
["12340", "10-05-2022", 'dress', "cloth", 175, 95 ]],
columns=["count", "date", "name", "category", "price", "revenue"])

['count'] = df['count'].astype(int)
df['month'] = pd.to_datetime(df['date']).dt.strftime('%b')
df.groupby(['category', 'name', 'month'])[['count', 'revenue', 'price']].sum().unstack(fill_value=0)

输出:

                 count revenue price
month Oct Oct Oct
category name
cloth dress 12355 190 330
shirt 9232 30 75
shoe boot 10413 245 570
sandal 211 20 210

关于python - 数据透视表和按月分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71662388/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com