【发布时间】:2020-04-29 00:16:25
【问题描述】:
我是优化新手,需要帮助改进此代码的运行时间。它完成了我的任务,但它需要永远。关于改进它以使其运行更快的任何建议?
代码如下:
def probabilistic_word_weighting(df, lookup):
# instantiate new place holder for class weights for each text sequence in the df
class_probabilities = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
for index, row in lookup.iterrows():
if row.word in df.words.split():
class_proba_ = row.class_proba.strip('][').split(', ')
class_proba_ = [float(i) for i in class_proba_]
class_probabilities = [a + b for a, b in zip(class_probabilities, class_proba_)]
return class_probabilities
两个输入df的样子是这样的:
df
index word
1 i havent been back
2 but its
3 they used to get more closer
4 no way
5 when we have some type of a thing for
6 and she had gone to the doctor
7 suze
8 the only time the parents can call is
9 i didnt want to go on a cruise
10 people come aint got
查找
index word class_proba
6231 been [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5.27899487]
8965 havent [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5.27899487]
3270 derive [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5.27899487]
7817 a [0.0, 0.0, 7.451379, 6.552, 0.0, 0.0, 0.0, 0.0]
3452 hello [0.0, 0.0, 0.0, 0.0, 0.000155327, 0.0, 0.0, 0.0]
5112 they [0.0, 0.0, 0.00032289312, 0.0, 0.0, 0.0, 0.0, 0.0]
1012 time [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5.27899487]
7468 some [0.000193199, 0.0, 0.0, 0.000212947, 0.0, 0.0, 0.0, 0.0]
6428 people [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5.27899487
5537 scuba [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 5.27899487
它所做的本质上是遍历查找中的每一行,其中包含一个单词及其相关的类权重。如果在 df.word 中的任何文本序列中找到该单词,则将 lookup.word 的 class_probabilities 添加到分配给 df.word 中每个序列的 class_probabilities 变量中。对于查找行的每次迭代,它都会遍历 df 中的每一行。
如何才能更快地做到这一点?
【问题讨论】:
-
这将适度优化您的
for循环:切换到for row in lookup.itertuples():而不是for index, row in lookup.iterrows():itertuples比iterrows更快确保您在集合上使用in运算符而不是比列表更快,因为成员资格测试在一组中更快。if row.word in df.words.split():,切换到word_set = set(df.words.split())(在for循环外定义一次)然后使用if row.word in word_set
标签: python pandas optimization nlp