Warm tip: This article is reproduced from stackoverflow.com, please click
aggregate pivot python

Pivot class attributes

发布于 2020-03-30 21:14:48

My goal is to achieve a pivot view of monthly expenditures.

I have a list of Expenditure objects which are simple:

Date, Subject, Amount
Date, Subject, Amount
Date, Subject, Amount

I need to have the result in the following way:

        Subject        Subject
Date   SUM(Amount)    SUM(Amount)
Date   SUM(Amount)    SUM(Amount)

How can I achieve such a result in Python? I know that in T-SQL, there is the pivot-function I can use for that, but I did not find anything for Python yet.

Questioner
Acroneos
Viewed
42
YOLO 2020-01-31 18:37

You can do this using pandas python library.

import pandas as pd
pivot_df = pd.pivot_table(data = df, index=['Date'], columns=['Subject'], values='Amount', aggfunc='sum')

Where dfis your dataframe containing data.