Cyrus Tung
Cyrus Tung

Reputation: 1

Understanding Pivot Tables in Python Pandas

I am trying to display a tabular pivot table for all combinations of 2 attributes. We'll name them "STORE_STATE" and "PRODUCT_CATEGORY_CODE". For each combo, I want to be able to show the SUM and MEAN for each of the columns. I have three different columns: we'll say they are "PRICE, QUANTITY and TOTAL_PAID_FOR_ITEM".

For now, I have been given a template of:

yearlyIncome = df.pivot_table(values = ["YearlyIncome"], index=["Gender", "MaritalStatus", "BikeBuyer"], aggfunc=np.mean) print(yearlyIncome)

This was part of a different sheet, but if I were to do it with the attributes that I have, I'm not so sure where I should start if I only have this to base it off of.

I want to be able to show the SUM and MEAN for each of the columns.

Upvotes: 0

Views: 38

Answers (1)

Manel Lopez
Manel Lopez

Reputation: 39

Try this:

index_cols = ['STORE_STATE', 'PRODUCT_CATEGORY_CODE']
cols = ['PRICE', 'QUANTITY', 'TOTAL_PAID_FOR_ITEM']
pqt = df.pivot_table(index=index_cols, values=cols, aggfunc=(np.sum, np.mean))
pqt.head()

Upvotes: 1

Related Questions