IPywidgets将小部件动态绑定到输出

问题描述

我正在为Jupyter笔记本编写一个函数用户可以在其中获取数据作为Pandas Dataframe(与该问题无关),并使用可以在需要时创建的过滤器进行显示

我的问题是我无法将交互过滤器“链接”到数据本身。在代码中手动定义过滤器没有问题,但没有从用户端定义。在发布到这里之前,我研究了Stackoverflow,Google,Github项目和文档中的许多问题。

这是POC:

import pandas as pd
import ipywidgets as widgets
from ipywidgets import *
from IPython.display import display
import numpy as np

np.random.seed(0)

# Data example
my_columns = list('ABCD')
df = pd.DataFrame(np.random.randint(0,100,size=(100,4)),columns=list('ABCD'))


# Encapsulate Table inside Output widget

table_out = widgets.Output()

with table_out:
    display(df)


# Filter for ints
def filter_int(column,x):
    return df.loc[df[column] > x]

# Our filter generator
def generate_filter(button):
    # Check if exist before creating
    if not select_deFinition.value in [ asd.children[0].description for asd in filters.children ]:
        # Not exist. Create this filter
        new_filter = interactive(
            filter_int,# Our filter for ints
            column=fixed(select_deFinition.value),# Which column as filter
            x=widgets.IntSlider(min=0,max=100,step=1,value=10,description=select_deFinition.value) # Value from the user
        )
        # Append created filter
        filters.children=tuple(list(filters.children) + [new_filter])

# Define button and event
button = widgets.Button(description="Add")
button.on_click(generate_filter)

# Define Dropdown 
select_deFinition = widgets.Dropdown(options=my_columns,layout=Layout(width='10%'))

# Put Dropdown and button together
choose_filter = widgets.HBox([select_deFinition,button])

# Where we will put all our filters
filters = widgets.HBox()

display(choose_filter,filters,table_out)

将创建以下内容

enter image description here

我能够为列动态创建过滤器,但是我不确定如何使它们更新表并链接在一起(因此表将基于多个过滤器进行更新)。

预期结果是能够为列AB创建过滤器,并使用它们定义的值更新表,如下图所示:

enter image description here

感谢您的帮助!

注意:最后一张图片是使用df.loc[(df['A'] > 22) & (df['B'] > 92)]

生成

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)