Python | Pandas.pivot_table ()



The levels in the pivot table will be stored in MultiIndex objects (hierarchical indexes) in the index and columns of the resulting DataFrame.

Parameters:

data: DataFrame
values: column to aggregate, optional
index: column, Grouper , array, or list of the previous
columns: column, Grouper, array, or list of the previous

aggfunc: function, list of functions, dict, default numpy.mean
– & gt; If list of functions passed, the resulting pivot table will have hierarchical columns whose top level are the function names.
– & gt; If dict is passed, the key is column to aggregate and value is function or list of functions

fill_value [scalar, default None]: Value to replace missing values ​​with
margins [boolean, default False]: Add all row / columns (eg for subtotal / grand totals)
dropna [boolean, default True]: Do not include columns whose entries are all NaN
margins_name [string, default `All`]: Name of the row / column that will contain the totals when margins is True.

Returns: DataFrame

Code:

# Create a simple data frame

 
# pandas import as pd

import pandas as pd

import numpy as np

 
# create data frame

df = pd.DataFrame ({ < code class = "string"> `A` : [ ` John` , `Boby` , ` Mina` , `Peter` , ` Nicky ` ],

  ` B` : [ `Masters` , `Graduate` , ` Graduate` , `Masters` , ` Graduate` ],

  ` C` : [ 27 , 23 , 21 , 23 , 24 ]})

 
df

# A simple pivot table should have a data frame
# and an index / index list.

table = pd.pivot_table (df, index = [ `A` , `B` ])

  
table

# Creates a pivot table data frame

table = pd.pivot_table (df, values ​​ = ` A` , index = [ `B` , `C` ],

  columns = [ `B` ], aggfunc np. sum )

 
table