【发布时间】:2018-03-11 11:24:49
【问题描述】:
我有一个由大字符串组成的数据集(从大约 300 个 pptx 文件中提取的文本)。 通过使用 pandas apply 我在每个字符串上执行“平均”函数,平均查找每个单词的对应词向量,将其与另一个向量相乘并返回平均相关性。
但是在大字符串上迭代和应用函数需要很多时间,我想知道我可以采取哪些方法来加速以下代码:
#retrieve word vector from words df
def vec(w):
return words.at[w]
#calculates the cosine distance between two vectors
def cosine_dist(a,b):
codi = 1 - spatial.distance.cosine(a, b)
return codi
#calculate the average cosine distance of the whole string and a given word vector
v_search = vec("test")
def Average(v_search, tobe_parsed):
word_total = 0
mean = 0
for word in tobe_parsed.split():
try: #word exists
cd = cosine_dist(vec(word), v_search)
mean += cd
word_total += 1
except: #word does not exists
pass
average = mean / word_total
return(average)
df['average'] = df['text'].apply(lambda x: average(x))
我一直在寻找编写代码的替代方法(例如 df.loc -> df.at)、cython 和多线程,但我的时间有限,所以我不想浪费太多时间在 less有效的方法。
提前致谢
【问题讨论】:
标签: python string performance parsing