3

I have the following sample code:

import pandas as pd 
import numpy as np
d = {'Fruit': ['Apples', 'Oranges', 'Apples', 'Kiwi', 'Kiwi'], 'Amount': 
     [10, 15, 65, 5, 13]}

df = pd.DataFrame(data=d)

table = pd.pivot_table(df, index='Fruit', aggfunc= np.sum)

The table results appear like this:

Fruit   Amount
Apples  75
Kiwi    18
Oranges 15

How do you add a grand total to the bottom? Also, I'd like to choose the order, example:

Fruit      Amount
Oranges    15
Apples     75
Kiwi       15
Total      105

How do I go about doing this? Thanks!

caddie
  • 169
  • 1
  • 3
  • 11

1 Answers1

5

Using margins

pd.pivot_table(df, index='Fruit', aggfunc= np.sum,margins = True,margins_name = 'Total')
Out[141]: 
         Amount
Fruit          
Apples       75
Kiwi         18
Oranges      15
Total       108
BENY
  • 317,841
  • 20
  • 164
  • 234
  • Excellent, thank you. How about manually choosing the order of the fruit instead of it being alphabetical? – caddie Nov 27 '18 at 18:46
  • Check with https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.Categorical.html and https://stackoverflow.com/questions/13838405/custom-sorting-in-pandas-dataframe – BENY Nov 27 '18 at 19:04
  • That did the trick! I used pd.Categorical to manual assign any sorting done to the Fruit series. Thanks so much! – caddie Nov 27 '18 at 19:15