[英]How to make pandas pivot table look like excel pivot table
pivot table in excel pivot 表在 excel
df=pd.DataFrame({'Fruit':['Apple', 'Orange', 'Apple', 'Apple', 'Orange', 'Orange'],
'Variety':['Fuji', 'Navel', 'Honeycrisp', 'Gala', 'Tangerine', 'Clementine'],
'Count':[2, 5, 5, 1, 8, 4]})
df_pvt=pd.pivot_table(df, index=['Fruit', 'Variety'], values=['Count'], aggfunc=np.sum)
df_final=pd.concat([
d.append(d.sum().rename((k, 'SubTotal')))
for k, d in df_pvt.groupby(level=0)
]).append(df_pvt.sum().rename(('','GrandTotal')))
df_final.to_excel('pvt.xlsx')
yield this exported to excel将此导出到 excel
1) How can I get the pivot table generated in pandas to look like the excel one? 1)我怎样才能让在 pandas 中生成的 pivot 表看起来像 excel 一个? 2) How do I get the subtotals in each of the top row like excel?
2)我如何获得像 excel 这样的顶行每一行的小计?
Thank you.谢谢你。
IIUC,国际大学联合会,
df_grand = df[['Count']].sum().T.to_frame(name='Count').assign(Fruit='Grand Total', Variety='').set_index(['Fruit','Variety'])
df_sub = df.groupby('Fruit')[['Count']].sum().assign(Variety='').set_index('Variety', append=True)
df_excel = df.set_index(['Fruit','Variety']).append(df_sub).sort_index().append(df_grand)
Output: Output:
Count
Fruit Variety
Apple 8
Fuji 2
Gala 1
Honeycrisp 5
Orange 17
Clementine 4
Navel 5
Tangerine 8
Grand Total 25
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.