简体   繁体   English

如何使用从小部件文本框中输入的单词搜索数据框,然后使用 python、ipywidgets 显示搜索结果?

[英]How to use a word typed in from a widget text box to search a data frame, then display the search result using python, ipywidgets?

I am just studying widget interaction in Python and Jupyter.我正在研究 Python 和 Jupyter 中的小部件交互。 My task is:我的任务是:

t=pd.DataFrame({'string':['i live here','you live in eltham','machine learning','learning english','go home','go back'],
                'number':[1,3,2,3,1,2],
                'word':['a','haha','runing over there','abcdefg','aaa','bye']})

import ipywidgets as widgets
from IPython.display import display

widgets.Text(
    value='Hello World',
    placeholder='Type something',
    description='keyword:',
    disabled=False
)

在此处输入图像描述

I need to type in some word, for example 'live', then the code will automatically search the data frame t and display all the rows with live in it.我需要输入一些单词,例如“live”,然后代码将自动搜索数据框 t 并显示其中包含 live 的所有行。

I am seeking some hints, because I do not know where to start.我正在寻求一些提示,因为我不知道从哪里开始。

finally figure out a simple example.最后想出一个简单的例子。 just put it here for someone who might need it.把它放在这里给可能需要它的人。

t=pd.DataFrame({'string':['i live here','you live in eltham','machine learning','learning english','go home','go back','live home'],
                'number':[1,3,2,3,1,2,4],
                'word':['a','haha','runing over there','abcdefg','aaa','bye','hou']})

def myFUN_searchString(value,string):
    s=string.split(' ')
    return value in s

def myFUN_search(value):
    t.loc[:,'Flag']=''
    t.loc[:,'Flag']=[myFUN_searchString(value,x) for x in t.loc[:,'string']]
    return t.loc[:,'Flag']

import ipywidgets as widgets
from IPython.display import display

keyword=widgets.Text(
    value='electricity',
    placeholder='Type something',
    description='keyword:',
    disabled=False
)
display(keyword)


button = widgets.Button(description="search")
display(button)

output = widgets.Output()

@output.capture()
def on_button_clicked(b):
    t.loc[:,'Flag']=myFUN_search(keyword.value)
    t1=t.loc[(t['Flag'])]
    t1.drop(['Flag'],axis=1,inplace=True)
    t1.reset_index(drop=True,inplace=True)
    if t1.shape[0]>30:
        t1=t1.loc[0:30]

    display(t1)

button.on_click(on_button_clicked)
display(output)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM