代码优化|比dataframe.iterrows()更快的方法?

问题描述 投票:0回答:1

我目前有一些使用df.iterrows()遍历熊猫数据帧的工作代码,但我正在寻求对其进行优化(使用df.apply()或切换到numpy数组)。我只是无法全神贯注于如何做到这一点。下面的代码/数据:

数据:

raw_text                  tokenized_text
hello, my name is tom     [hello, my, name, is, tom]
hello, my name is jeff    [hello, my, name, is, jeff]

要解决的问题:将tokenized_text列与一个列表进行比较,并计算tokenized_text列与该列表之间的重叠单词数。下面的代码:

代码:

def list_compare(lst1, lst2):
        freq = len(list(set(lst1) & set(lst2)))
        return freq

lst = ['hello', 'my']
freq_counts = []

for val in df.iterrows():
    freq_counts.append(list_compare(lst, val[1][tokenized_text])

df['freq_counts'] = freq_counts

问题:有没有一种更快的方法可以使用apply()函数或numpy数组来完成上述操作?

谢谢!

python pandas dataframe apply
1个回答
0
投票

IIUC,可以将applyset交集一起使用:

df = pd.DataFrame({"raw_text":["hello, my name is tom","hello, my name is jeff"]})
df["tokenized_text"] = df["raw_text"].str.findall("\w+")

lst = ['hello', 'my']

df["count"] = df["tokenized_text"].apply(lambda x: len(set(x).intersection(set(lst))))

print (df)

#
                 raw_text               tokenized_text  count
0   hello, my name is tom   [hello, my, name, is, tom]      2
1  hello, my name is jeff  [hello, my, name, is, jeff]      2
© www.soinside.com 2019 - 2024. All rights reserved.