我正在尝试使用Ipywidget创建一个动态筛选。此处的dynamic一词指的是:如果在一个小部件中选择了一个选项,它将影响其余小部件的选择。
以下是用于复制的玩具数据集。
toy_data = pd.DataFrame({"LETTER": ["A", "B", "A","B","A", "B", "A","B"],
"PLANT": ["Orange", "Carrots", "Lemon","Potato","Pomelo","Yam","Lime","Radish"],
"NUMBER": [1,2,3,4,5,6,7,8]})创建小部件:
letter_var = widgets.Dropdown(
description="Letter: ",
options=toy_data.LETTER.unique(),
value="A",
)
def letter_filtering(change):
clear_output(wait = True)
letter = letter_var.value
new_toy_data = toy_data[toy_data.LETTER == str(letter)]
plant_var = widgets.Dropdown(description="Plant: ", options=new_toy_data.PLANT.unique(), value="Orange")
return plant_varletter_filtering函数的目的是过滤植物妻子的选择。也就是说,如果字母B是为letter_var选择的,则plant_var中的选择将仅限于字母B,但在实现时,
widgets.HBox([letter_var,letter_filtering])我收到了一个特质错误。
TraitError: The 'children' trait of a HBox instance contains an Instance of a TypedTuple which expected a Widget, not the function 'letter_filtering'.我想我不知道该怎么做了。
发布于 2022-02-03 14:59:25
我不熟悉小部件机制,但是您可以通过“交互”功能来实现这一点,我认为这也更简单:
from ipywidgets import interact, fixed
toy_data = pd.DataFrame({"LETTER": ["A", "B", "A","B","A", "B", "A","B"],
"PLANT": ["Orange", "Carrots", "Lemon","Potato","Pomelo","Yam","Lime","Radish"],
"NUMBER": [1,2,3,4,5,6,7,8]})
def inner_fn(plant, df_in):
df_ = df_in if plant == 'ALL' else df_in[df_in['PLANT'] == plant]
return df_
def outer_fn(letter):
df_ = toy_data if letter == 'ALL' else toy_data[toy_data['LETTER'] == letter]
plants = ['ALL'] + sorted(df_['PLANT'].unique())
interact(inner_fn, plant=plants, df_in=fixed(df_))
letters = ['ALL'] + sorted(toy_data['LETTER'].unique())
interact(outer_fn, letter=letters)这将在“信函”下拉栏下创建一个“植物”下拉列表,如下所示:

当选择一封信时,植物列表会更新如下:

第二个下拉框的额外缩进是一个提示,这是一种嵌套机制,而且无可否认,这使得这项技术有点不美观。
https://stackoverflow.com/questions/68948012
复制相似问题