[問題]請教如何加快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