我有以下示例資料
df = pd.DataFrame(columns=["date", "item", "qty"], data=[['2022-10-11','apple',2],['2022-10-12','orange',4],['2021-11-01','apple',5],['2021-11-02','orange',8],['2021-12-01','apple',9],['2021-12-02','orange',3],['2022-01-01','banana',2],['2022-01-02','apple',1],['2022-01-03','orange',6],['2022-02-02','apple',7],['2022-02-03','orange',4]])
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
看起來像這樣

我想將行分組為年和月,將專案分組為列,并帶有行和列小計。使用 Excel 資料透視表,可以這樣做:

pd.pivot_table 方法
現在,使用
pd.pivot_table(df, values='qty', index='date', columns='item', aggfunc='sum', fill_value='', margins=True)
我得到了一些接近但沒有年份和月份行分組的東西:

如果我替換index='date'為index=[pd.Grouper(key='date', freq='M')]我得到一個錯誤:
KeyError: "[TimeGrouper(key='date', freq=<MonthEnd>, axis=0, sort=True, closed='right', label='right', how='mean', convention='e', origin='start_day')] not in index"
如果我保留index=[pd.Grouper(key='date', freq='M')]但洗掉margins=True,我會得到資料透視表但沒有小計:
pd.pivot_table(df, values='qty', index=[pd.Grouper(key='date', freq='M')], columns='item', aggfunc='sum', fill_value=0) #removed margins=True

我怎樣才能同時擁有年和月分組以及小計?
分組方法
作為替代方案,我嘗試按如下方式使用 groupby。但是,這些專案顯示為行而不是列,我不確定如何獲取行(和列)小計。
df.groupby([df.date.dt.year, df.date.dt.month, 'item']).agg({'qty':'sum'})

uj5u.com熱心網友回復:
用于DataFrame.assign輔助列year并month傳遞給pivot_table:
(df.assign(year = df.date.dt.year,month = df.date.dt.month)
.pivot_table(values='qty',
index=['year','month'],
columns='item',
aggfunc='sum',
fill_value='',
margins=True))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/525783.html
