Data selecting with widget checkbox

I am trying to write an interactive python script (jupiter notebook) that lets me select different parts of a pandas df. Later I want to use this in combination with an OLS regression to selct which of the 6 parts from the original df get selected for the regresion. Each part coresponds to one year of data.

Right now i am just trying to make it work, so I want to print the df with the updated numbers.

selected_data is created and printed, but only with the column headers. The checkboxes also appear, but when i check one of the boxes, the printed df ist not being updated.

Every help is welcome.

input is : adj_data outout should be : selected_data

# Function to update the dataset based on checkbox selection
def update_dataset(selected_checkboxes):
    selected_data = pd.DataFrame(columns=adj_data.columns)  # Create empty DataFrame with the correct column headers
    if 1 in selected_checkboxes:
        selected_data = pd.concat([selected_data, adj_data.iloc[:400]])
    if 2 in selected_checkboxes:
        selected_data = pd.concat([selected_data, adj_data.iloc[400:799]])
    if 3 in selected_checkboxes:
        selected_data = pd.concat([selected_data, adj_data.iloc[799:1198]])
    if 4 in selected_checkboxes:
        selected_data = pd.concat([selected_data, adj_data.iloc[1198:1597]])
    if 5 in selected_checkboxes:
        selected_data = pd.concat([selected_data, adj_data.iloc[1597:1996]])
    if 6 in selected_checkboxes:
        selected_data = pd.concat([selected_data, adj_data.iloc[1996:2394]])
    return selected_data


# Create checkboxes
checkbox_widgets = [widgets.Checkbox(value=False, description=f'{i+1}') for i in range(6)]

# Create observable output for the checkboxes
checkbox_output = widgets.VBox(checkbox_widgets)
checkbox_output

# Register the callback function for the checkbox changes
for checkbox in checkbox_widgets:
    checkbox.observe(update_regression, 'value')

# Display of checkboxes and regression graphic
display(checkbox_output)
print(selected_data)

The print is only being called once, and so will likely never update.

To get something that live updates, one can use an Output widget:

dataframe_preview = Output()
# ...
def update_dataset(selected_checkboxes):
   # ...
   dataframe_preview.clear_output()
   with dataframe_preview:
      display(selected_data)
# ...
display(checkbox_output, dataframe_preview)

For better support of dataframes (and numpy arrays) as traits, perhaps have a look at traittypes… though keep in mind that these don’t magically make subsets of dataframes evented, just when the entire value is set.

1 Like