10

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)
tripleee
  • 175,061
  • 34
  • 275
  • 318
math
  • 1,868
  • 4
  • 26
  • 60

1 Answers1

14
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?

ac24
  • 5,325
  • 1
  • 16
  • 31
  • 3
    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. – above_c_level Sep 10 '21 at 16:32