Reputation: 2814
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 ?
Upvotes: 2
Views: 1473
Reputation: 27370
The first problem is that this function doesn't accept a values
kwarg, but rather vals
.
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 the pandas
pivot table's aggfunc
argument. If you expect to only have a single value then something like pivot_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 Count
of input records per cell. Count
doesn't accept any arguments, so passing in vals
on its own won't change that. First
does accept arguments, so passing in vals=['cost']
will cause each cell to contain the first value of cost
(ordered via "natural sort") per cell.
Upvotes: 3