繁体   English   中英

将 function 应用于 dask dataframe 中的列的最有效方法是什么?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM