Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a pandas dataframe within a VBOX using ipywidgets

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)
like image 585
math Avatar asked Apr 11 '20 09:04

math


1 Answers

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?

like image 185
ac24 Avatar answered Sep 18 '22 00:09

ac24