12

i would like to display a pandas dataframe in a interactive way using ipywidgets. So far the code gets some selections and then does some calculation. For this exmaple case, its not really using the input labels. However, my problem is when I would like to display the pandas dataframe, it's not treated as widget. But how can I nicely display then pandas dataframe using widgets? At the end I would like to have a nice table in the main_box

here is a code exmaple, which works in any jupyter notebook

import pandas as pd
import ipywidgets as widgets

def button_run_on_click(_):
    status_label.value = "running...."

    df = pd.DataFrame([[1,2,3],[4,5,6],[7,8,9]])
    status_label.value = ""

    result_box = setup_ui(df)

    main_box.children = [selection, button_run, status_label, result_box]


def setup_ui(df):

    return widgets.VBox([df])

selection_box = widgets.Box()
selection_toggles = []
selected_labels = {}
default_labels = ['test1', "test2"]

labels = {"test1": "test1", "test2": "test2", "test3": "test3"}

def update_selection(change):
    owner = change['owner']
    name = owner.description

    if change['new']:
        owner.icon = 'check'
        selected_labels[name] = labels[name]
    else:
        owner.icon = ""
        selected_labels.pop(name)

for k in sorted(labels):
    o = widgets.ToggleButton(description=k)
    o.observe(update_selection, 'value')
    o.value = k in default_labels
    selection_toggles.append(o)
    selection_box.children = selection_toggles

status_label = widgets.Label()
status_label.layout.width = '300px'

button_run = widgets.Button(description="Run")
main_box = widgets.VBox([selection_box, button_run, status_label])
button_run.on_click(button_run_on_click)
display(main_box)

1 Answer 1

14
+50
from IPython.display import display
import ipywidgets as widgets


def setup_ui(df):
    
    out = widgets.Output()
    with out:
        display(df)
    return out

If you change your setup_ui function to this, you can return an Output widget with your dataframe.

BUT, in your button_run_on_click function it appears selection is not defined. Should this be something else?

Sign up to request clarification or add additional context in comments.

1 Comment

Hint: If you are using the same Output() widget with a changing dataframe, don't forget to use the clear paramter in the display() function, e.g. display(df, clear=True). Otherwise it will display the old and the new dataframe in the Output widget.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.