Good question. You’ll have to somehow get the data formatted as a list of dicts like:
[
{'column-1': 3, 'column-2': 5},
{'column-1': 1, 'column-2': 3},
]
So, for pivot_table
, try:
pt.reset_index().to_dict('rows')
Full example:
import pandas as pd
import numpy as np
>>> df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo",
... "bar", "bar", "bar", "bar"],
... "B": ["one", "one", "one", "two", "two",
... "one", "one", "two", "two"],
... "C": ["small", "large", "large", "small",
... "small", "large", "small", "small",
... "large"],
... "D": [1, 2, 2, 3, 3, 4, 5, 6, 7]})
>>> table = pd.pivot_table(df, values='D', index=['A', 'B'],
... columns=['C'], aggfunc=np.sum)
>>> table.reset_index().to_dict('rows')
[{'A': 'bar', 'B': 'one', 'large': 4.0, 'small': 5.0},
{'A': 'bar', 'B': 'two', 'large': 7.0, 'small': 6.0},
{'A': 'foo', 'B': 'one', 'large': 4.0, 'small': 1.0},
{'A': 'foo', 'B': 'two', 'large': nan, 'small': 6.0}]
This is a good reference: http://www.jeannicholashould.com/tidy-data-in-python.html