I have a pandas DataFrame with 3 columns : product, region, and cost.
I want to display a pivot table using pivottable.js in a Jupyter notebook such that product are rows, region are columns and cost are values.
I have tried :
from pivottablejs import pivot_ui
import pandas as pd
df = pd.DataFrame({'region':['N', 'S', 'W', 'E', 'N', 'S', 'W', 'E'],
'product':['P1', 'P1', 'P1', 'P1', 'P2', 'P2', 'P2', 'P2'],
'cost':[10, 13, 17, 28, 29, 23, 17, 18]})
pivot_ui(df, rows=['product'], cols=['region'], values=['cost'])
But this does not work, since there does not exist a values attribute for pivot_ui().
How to do that ?
The first problem is that this function doesn't accept a
valueskwarg, but rathervals.The second issue you'll face is that you'll need to specify an aggregation function (the default is
Count) to summarize your values. This is sort of similar to thepandaspivot table'saggfuncargument. If you expect to only have a single value then something likepivot_ui(df, rows=['product'], cols=['region'], vals=['cost'], aggregatorName='First')should do the trick.By way of explanation, your code above is just providing the
Countof input records per cell.Countdoesn't accept any arguments, so passing invalson its own won't change that.Firstdoes accept arguments, so passing invals=['cost']will cause each cell to contain the first value ofcost(ordered via "natural sort") per cell.