Tengo los siguientes datos:
Employee Account Currency Amount Location Test 2 Basic USD 3000 Airport Test 2 Net USD 2000 Airport Test 1 Basic USD 4000 Town Test 1 Net USD 3000 Town Test 3 Basic GBP 5000 Town Test 3 Net GBP 4000 Town
Puedo manejar pivotar haciendo lo siguiente:
import pandas as pd table = pd.pivot_table(df, values=['Amount'], index=['Location', 'Employee'], columns=['Account', 'Currency'], fill_value=0, aggfunc=np.sum, dropna=True)
Salida:
Amount Account Basic Net Currency GBP USD GBP USD Location Employee Airport Test 2 0 3000 0 2000 Town Test 1 0 4000 0 3000 Test 3 5000 0 4000 0
¿Cómo puedo lograr el subtotal por ubicación y luego un total general final en la parte inferior? Salida deseada:
Amount Account Basic Net Currency GBP USD GBP USD Location Employee Airport Test 2 0 3000 0 2000 Airport Total 3000 0 2000 Town Test 1 0 4000 0 3000 Test 3 5000 0 4000 0 Town Total 5000 4000 4000 3000 Grand Total 5000 7000 4000 5000
Traté de seguir lo siguiente . Pero no da la salida deseada. Gracias.
tu mesa pivotante
table = pd.pivot_table(df, values=['Amount'], index=['Location', 'Employee'], columns=['Account', 'Currency'], fill_value=0, aggfunc=np.sum, dropna=True, ) print(table) Amount Account Basic Net Currency GBP USD GBP USD Location Employee Airport Test 2 0 3000 0 2000 Town Test 1 0 4000 0 3000 Test 3 5000 0 4000 0
pandas.concat
pd.concat([ d.append(d.sum().rename((k, 'Total'))) for k, d in table.groupby(level=0) ]).append(table.sum().rename(('Grand', 'Total'))) Amount Account Basic Net Currency GBP USD GBP USD Location Employee Airport 2 0 3000 0 2000 Total 0 3000 0 2000 Town 1 0 4000 0 3000 3 5000 0 4000 0 Total 5000 4000 4000 3000 Grand Total 5000 7000 4000 5000
para la posteridad
construir sub totales
tab_tots = table.groupby(level='Location').sum() tab_tots.index = [tab_tots.index, ['Total'] * len(tab_tots)] print(tab_tots) Amount Account Basic Net Currency GBP USD GBP USD Location Airport Total 0 3000 0 2000 Town Total 5000 4000 4000 3000
todos juntos
pd.concat( [table, tab_tots] ).sort_index().append( table.sum().rename(('Grand', 'Total')) )
Aquí hay dos líneas que deberían funcionar. El método loc
permite subordinar las filas por sus índices, ya que hay un índice múltiple, yo introduzco loc
una tupla para los puntos de inserción de la fila en el lado izquierdo. Al usar ‘Town’ sin la tupla, se extraen todos los niveles correspondientes del índice.
En la segunda línea, tengo que quitar la última fila del DataFrame de la sum
y lo hago usando su atributo de forma.
In[1]: table.loc[('Town Total', ''),:] = table.loc['Town'].sum() table.loc[('Grand Total', ''),:] = table.iloc[:(table.shape[0]-1), :].sum() In[2]: table Out[2]: Amount Account Basic Net Currency GBP USD GBP USD Location Employee Airport 2 0 3000 0 2000 Town 1 0 4000 0 3000 3 5000 0 4000 0 Town Total 5000 4000 4000 3000 Grand Total 5000 7000 4000 5000