[问题]请教如何加快dataframe的条件判断

楼主: liquidbox (樹枝擺擺)   2023-05-14 18:13:58
请问,我有一个近万个由不重复字串组成的list叫kw_list,以及一个df
范例是['book','money','future','file']
Index sentence
1 This is a book
2 back to the future
3 replace the file
4 come on
5 have a nice weekend
我想要把list中的字串逐一拉出来,
跟sentence那个字段比较,如果sentence字段有包含该字串(近万个都要逐一比对)
就标上True,否则就False
我建了一个近万个column的新dataframe,字段是kw_list
然后跟原本的df合并起来,
然后再写个条件判断式,若该笔资料的sentence包含该字串,
那个column就标上True,不然就False
于是会变成
Index sentence book money future file
1 This is a book TRUE FALSE FALSE FALSE
2 back to the future FALSE FALSE TRUE FALSE
3 replace the file FALSE FALSE FALSE TRUE
4 come on FALSE FALSE FALSE FALSE
5 have a nice weekend FALSE FALSE FALSE FALSE
不意外地,我用循环去判断,跑几小时都跑不出结果,如下:
for kw in kw_list:
df.loc[df['sentence'].str.contains(kw),df[kw]]=True
我觉得我把同样的东西丢到Excel用函数算可能都比较快,
请问有什么方法改写,让这个df的运算速度加快吗
作者: celestialgod (天)   2023-05-14 18:32:00
作者: poototo (poototo)   2023-05-14 19:40:00
拿sentence的word来判断是否存在于kw_list
作者: lycantrope (阿宽)   2023-05-14 21:31:00
pandas: df[kw]=df["sentence"].str.contains(kw)for kw in df:

Links booklink

Contact Us: admin [ a t ] ucptt.com