Is there a way to incorporate pivottablejs in streamlit

I am learning to use streamlit and was trying to see if there was any way pivottablejs could be rendered.

I can use it in a jupyter notebook and was trying to get it to render similarly in streamlit.

Thanks.

Hi @sks -

Try this (untested):


import streamlit as st
import streamlit.components.v1 as components
from pivottablejs import pivot_ui

components.html(pivot_ui(df))

Looking at the pivottablejs library for Python, it looks like they return an IFrame that Jupyter Notebooks know how to deal with. components.html for Streamlit is the same basic idea.

If it turns out to not work, it looks like it wouldn’t be very hard to extend support to Streamlit using our Components framework.

1 Like

Hi Randy,

Thanks for looking into this and your prompt reply. Tried it real quick and got this traceback.

Got this error

Traceback:
File "venv/lib/python3.7/site-packages/streamlit/ScriptRunner.py", line 319, in _run_script
    exec(code, module.__dict__)
File "streamlit_app.py", line 78, in <module>
    components.html(pivot_ui(cb_block_devices_df))
File "venv/lib/python3.7/site-packages/streamlit/DeltaGenerator.py", line 127, in wrapped_method
    return dg._enqueue_new_element_delta(marshall_element, delta_type, last_index)
File "venv/lib/python3.7/site-packages/streamlit/DeltaGenerator.py", line 398, in _enqueue_new_element_delta
    rv = marshall_element(msg.delta.new_element)
File "venv/lib/python3.7/site-packages/streamlit/DeltaGenerator.py", line 125, in marshall_element
    return method(dg, element, *args, **kwargs)
File "venv/lib/python3.7/site-packages/streamlit/DeltaGenerator.py", line 1616, in _html
    scrolling=scrolling,
File "venv/lib/python3.7/site-packages/streamlit/elements/iframe_proto.py", line 54, in marshall
    proto.srcdoc = srcdoc```

It’s a little awkward because the pivot table dynamically resizes, but this works on my computer

import streamlit as st
import streamlit.components.v1 as components
from pivottablejs import pivot_ui
import pandas as pd

iris = pd.read_csv(
    "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv"
)

t = pivot_ui(iris)

with open(t.src) as t:
    components.html(t.read(), width=900, height=1000, scrolling=True)

It wouldn’t be much to either add this to the pivottablejs Python package, or create a static Component for this.

2 Likes

That worked! Thank you so much for your support and help. Much appreciated.

2 Likes

Fab! Thanks Randy (and Nicolas.Kruchten for creating the lib!)

If only one could export the pivot output… one can dream! :slight_smile:

Charly

If it’s possible from the JS library, that would be a nice bi-drectional component feature. Pivot in the browser, return the result back somehow (JSON?)

1 Like

Wow! I didn’t realise that!

The TSV export on the JS lib is actually very handy!

Folks can try it here -> https://pivottable.js.org/examples/mps_export.html