I'm trying to include subtotals in my pivot_table.
Pivot table code
# Specify the aggregation functions
aggfunc = {'amt': 'sum', 'llp': 'first'}
Pivot and calculate aggregated values using aggfunc
Pivoted_data = pd.pivot_table(pivot_data,index=['Expense', 'Name', 'Currency', 'Facility'],values= ["amt", "llp"], aggfunc= aggfunc, dropna=True)
I have this code which works but my output is creating a long string rather than separate columns for each of the indexes.
sub = pd.concat([d.append(d.sum().rename((k,'Total')))
for k, d in pivoted_data.groupby(level=0)])
.append(pivoted_data.sum().rename(('Grand','Total'))) ```
How can I have it so the indexes aren't merged together as a list in one cell when exporting to excel?
So I want this:
| Expense | Name | Currency | Name | Amt | LLP |
|---|---|---|---|---|---|
| A | Xy | Eur | Xyz | 7059 | 0 |
| A Total | 7059 | 0 | |||
| B | Zz | GBP | Xyzs | 5803 | 50 |
| B | Z2z | GBP | Xyzs123 | 9586 | 6000 |
| B Total | 15389 | 6050 |
But my code is giving me this.
| Amt | LLP | ||
|---|---|---|---|
| A, Xy, Eur,Xyz | 7059 | 0 | |
| A Total | 7059 | ||
| B, Zz, GBP, Xyzs | 5803 | 50 | |
| B, Z2z, GBP, Xyzs123 | 9586 | 6000 | |
| B Total | 15389 |