
I am looking for a solution to sort a pandas pivot table, as it is possible in Excel pivot tables, according to the aggregated values and thereby determine the order of the first level.
I have found a solution that uses pd.append.
A warning tells me that pd.append will not be available in the future and that I should therefore use pd.concat.
I have not managed to solve my problem with pd.concat.
This is the solution with pd.append
>Solution :
You should use concat this way:
out = pd.concat([
df_pivot.iloc[:-1]
.assign(sort=lambda x: x['Totals'].groupby(level=0).transform('sum'))
.sort_values(['sort','Name','Totals'],
ascending=[False,True,False], kind='mergesort')
.drop('sort', axis=1),
df_pivot.iloc[[-1]] # slicing as DataFrame, not Series
])
Output:
Year 2019 2020 Totals
Name A B
Brian foo one 20 0 20
zz xy 10 0 10
bar two 0 9 9
one 0 8 8
zz zz 0 5 5
Peter foo one 20 0 20
bar two 0 9 9
one 6 0 6
Amy foo two 11 0 11
one 4 0 4
Totals 71 31 102