python - sum of rows/columns/total appended in pivot -


i using below pivot_table command meet requirement of having result in following format

active_def = pd.pivot_table(data, index = 'inmonth', columns= 'outmonth', aggfunc= 'count')['id'] 

i need column towards end of pivot table having row totals. row towards end having column totals , 1 cell having sum of values in table. (in simple words, similar pivot in excel). there pythonized way it? know can use data.sum(axis=0/1) obtain individually, but, looking better way it.

thanks!

pivot table results

use per @parfait suggestion:

active_def = pd.pivot_table(data, index = 'inmonth', columns= 'outmonth', aggfunc= 'count', margins=true)['id'] 

or

you can use one-liner:

data setup

df = pd.dataframe(data=np.triu(np.random.randint(0,13,(12,12))),                   columns=np.arange(1,13),                    index=np.arange(1,13)) 

calculate grand totals rows, columns, , entire dataframe:

df.append(pd.series(df.sum(),name='total'))\   .assign(total=df.sum(1))\   .set_value('total','total',df.values.sum()) 

output:

       1   2   3   4   5   6   7   8   9  10  11  12  total 1      4   3   6  12   5   9   0  12   1  10   8  10   80.0 2      0   9   8   1   5   1   5  10   7   1   9   2   58.0 3      0   0   2  11   4   0   2   5   4  12   1   7   48.0 4      0   0   0  11   9   2  10   3   0   5   2  10   52.0 5      0   0   0   0   7  12  10  11  12   5   6   0   63.0 6      0   0   0   0   0  12   1   4   1   2  11   0   31.0 7      0   0   0   0   0   0   8  12   8   7   2   1   38.0 8      0   0   0   0   0   0   0  12   7   0   5   9   33.0 9      0   0   0   0   0   0   0   0  12   4  10   9   35.0 10     0   0   0   0   0   0   0   0   0   3   7   1   11.0 11     0   0   0   0   0   0   0   0   0   0   8   2   10.0 12     0   0   0   0   0   0   0   0   0   0   0   5    5.0 total  4  12  16  35  30  36  36  69  52  49  69  56  464.0 

Comments

Popular posts from this blog

service - Android MediaPlayer calls onCompletion before it already finished -

javascript - Training Neural Network to play flappy bird with genetic algorithm - Why can't it learn? -

javascript - Create a stacked percentage column -