簡體   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?

我正在研究 Python 和 Jupyter 中的小部件交互。 我的任務是:

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
)

在此處輸入圖像描述

我需要輸入一些單詞,例如“live”,然后代碼將自動搜索數據框 t 並顯示其中包含 live 的所有行。

我正在尋求一些提示,因為我不知道從哪里開始。

最后想出一個簡單的例子。 把它放在這里給可能需要它的人。

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