我想應用形式的函式(真正的函式有 5 個引數,但假設它只有 2 個)
def func(text,model):
return model[text]
通過以下方式到資料框:
model = something
df[col2]= df[col1].apply(lambda text: func(text, model)
這作業正常,但速度很慢。這是一個運行良好的更快版本,除非該函式是 lambda 函式。
def apply(func, data):
with Pool(cpu_count()) as pool:
return list(tqdm.tqdm(pool.imap(func, data), total=len(data)))
它拋出以下錯誤:
PicklingError: Can't pickle <function <lambda> at 0x7fe59c869e50>: attribute lookup <lambda> on __main__ failed
我的解決方案:為了更快地應用此函式,我使用了以下技巧:重新定義函式,使第二個引數為默認值,并在加載函式之前定義值模型。
model = something
def func(text,model=model):
return model[text]
這很好用,但是我覺得這有點難看。我想知道是否有其他方法可以做到這一點。我也嘗試過創建一個類
class Applyer:
def __init__(self,model):
self.model = model
def func(self,text):
return model[text]
如果我創建一個實體然后應用這樣的函式:
model=something
applyer = Applyer(model)
apply(applyer.func,df[col1])
這可行,但它甚至比使用普通應用(沒有多處理)還要慢。這是我的兩次嘗試。
uj5u.com熱心網友回復:
您可以使用固定引數部分評估您的函式,然后使用缺少的變數引數呼叫它functools.partial:
from functools import partial
partial_func = partial(func, model=some_model)
# now you can call it directly, providing the missing parameter(s):
partial_func(some_text)
# and you can apply it without a lambda:
df[col1].apply(partial_func)
這應該已經加快了運行時間。我沒有嘗試將其并行化,但由于它是一個簡單的函式呼叫,因此這個問題中給出的方法也應該有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/420937.html
標籤:
上一篇:用于seaborn熱圖的二維陣列中的BinDataFrame
下一篇:計數值在列中連續出現的次數
