我想在執行函式時顯示兩個選項的 df 中創建新列。
我有兩個清單:
lista = [A, B, C, D]
listb = [would not, use to, manage to, when, did not]
我想找到可以出現的第一個單詞lista并將其回傳到一個名為“Effect”的新列中。如果未找到,則搜索 from 的值listb并列印第一個遇到的 fromlistb以及接下來的 2 個字串。
例子:

我嘗試過這樣的事情:
def matcher(Description):
for i in lista:
if i in Description:
return i
return "Not found"
def matcher(Description):
for j in listb:
if j in Description:
return j 1
return "Not found"
df["Effect"] = df.apply(lambda i: matcher(i["Description"]), axis=1)
df["Effect"] = df.apply(lambda j: matcher(j["Description"]), axis=1)
uj5u.com熱心網友回復:
下面的代碼應該做你想要實作的目標:
def matcher(sentence):
match_list = [substr for substr in lista
if substr in [ word
for word in sentence.replace(',',' ').split(" ")]]
if match_list: # list with items evaluates to True, empty list to False
return match_list[0]
match_list = [substr for substr in listb if ' ' substr ' ' in sentence]
if match_list:
substr = match_list[0]
return substr " " sentence.split(substr)[-1].replace(',',' ').strip().split(" ")[0]
return "Not found"
df["Effect"] = df.Description.apply(matcher)
如果句子中包含多個“,”,請考慮使用正則運算式替換,而不是使用.replace(',',' ')空格代替句子中的所有非字母字符(以便保證單詞保持分隔),并注意一些不尋常的事實子字串和句子的情況可能會產生意想不到的副作用。
uj5u.com熱心網友回復:
您可以同時執行這兩項操作:
def matcher(Description):
w = [i for i in lista if i in Description]
w.extend( [i for i in listb if i in Description] )
if not w:
return "Not found"
else:
return ' '.join(w)
df["Effect"] = df.apply(lambda i: matcher(i["Description"]), axis=1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/527563.html
上一篇:達到條件時如何呼叫函式?
