![](/img/trans.png)
[英]In Python/Pandas, what is the most efficient way, to apply a custom function, to a column of a dataframe, where the input includes strings?
[英]What is the most efficient method to apply a function to a column in a dask dataframe?
我有一個 function 可以標記元組中的單詞:
def get_word_tokens(tokens):
words = [token[0] for token in tokens]
return words
我想將此應用於 dask dataframe 中的列並創建一個新列,例如
df1
#phrase tokens
0 call CHRIS MOBILE. [(call, 0, 4),
(CHRIS, 5, 10),
(MOBILE, 11, 17)]
1 call Tod Sarks [(call, 0, 4),
(Tod, 5, 8),
(arks, 9, 14)]
創建列詞
df1
#phrase tokens words
0 call CHRIS MOBILE. [(call, 0, 4), call, CHRIS, MOBILE
(CHRIS, 5, 10),
(MOBILE, 11, 17)]
1 call Tod Sarks [(call, 0, 4), call, Tod, Sarks
(Tod, 5, 8),
(Sarks, 9, 14)]
我努力了:
df['words'] = df.apply(lambda row: get_word_tokens(df['tokens']), axis = 1)
這似乎有效,但需要很長時間才能運行? 有沒有更快的方法?
您將df['tokens']
傳遞給 function,這是完整的列。 這應該有效:
def get_word_tokens(tokens):
words = [token[0] for token in tokens]
return words
data = [
['call CHRIS MOBILE.', [('call', 0, 4),
('CHRIS', 5, 10),
('MOBILE', 11, 17)]],
['call Tod Sarks', [('call', 0, 4),
('Tod', 5, 8),
('arks', 9, 14)]],
]
import pandas as pd
df = pd.DataFrame(data, columns=['phrase', 'tokens'])
df = pd.concat([df,df,df,df, df, df])
import dask.dataframe as dd
ddf = dd.from_pandas(df, npartitions=2)
def get_word_tokens_df(df):
df['words'] = df['tokens'].apply(get_word_tokens)
return df
ddf = ddf.map_partitions(get_word_tokens_df)
ddf.compute()
嘗試這個:
df.join(df['tokens'].str.extractall(r'([A-Za-z]\w+)').groupby(level=0).agg(','.join).squeeze().rename('words'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.