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')
1)如何获得在熊猫中生成的数据透视表,使其看起来像Excel一样? 2)如何获得像excel这样的每一行的小计?
谢谢。
答案 0 :(得分:0)
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)
输出:
Count
Fruit Variety
Apple 8
Fuji 2
Gala 1
Honeycrisp 5
Orange 17
Clementine 4
Navel 5
Tangerine 8
Grand Total 25