【问题标题】:How to optimize this nested loop code dealing with pandas dataframes如何优化处理熊猫数据帧的嵌套循环代码
【发布时间】: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(): itertuplesiterrows 更快确保您在集合上使用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


【解决方案1】:

IIUC,您在函数中使用df.apply,但您可以这样做。这个想法不是每次找到相应的单词时都对lookup的行重做操作,而是做一次并重塑df,以便能够执行矢量化操作

1:用str.splitstackto_frame重塑df的列字,为每个字换行:

s_df = df['words'].str.split(expand=True).stack().to_frame(name='split_word')
print (s_df.head(8))
    split_word
0 0          i
  1     havent
  2       been
  3       back
1 0        but
  1        its
2 0       they
  1       used

2:通过set_index word 列、str.stripstr.splitastype 重塑lookup,以得到一个数据框,其中 word 作为索引,class_proba 的每个值在一列中

split_lookup = lookup.set_index('word')['class_proba'].str.strip('][')\
                     .str.split(', ', expand=True).astype(float)
print (split_lookup.head())
          0    1         2      3         4    5    6         7
word                                                           
been    0.0  0.0  0.000000  0.000  0.000000  0.0  0.0  5.278995
havent  0.0  0.0  0.000000  0.000  0.000000  0.0  0.0  5.278995
derive  0.0  0.0  0.000000  0.000  0.000000  0.0  0.0  5.278995
a       0.0  0.0  7.451379  6.552  0.000000  0.0  0.0  0.000000
hello   0.0  0.0  0.000000  0.000  0.000155  0.0  0.0  0.000000

3:Merge 两者都有,drop 是不必要的列,groupby level=0 是 dfsum 的原始索引

df_proba = s_df.merge(split_lookup, how='left',
                      left_on='split_word', right_index=True)\
               .drop('split_word', axis=1)\
               .groupby(level=0).sum()
print (df_proba.head())
          0    1         2         3    4    5    6         7
0  0.000000  0.0  0.000000  0.000000  0.0  0.0  0.0  10.55799
1  0.000000  0.0  0.000000  0.000000  0.0  0.0  0.0   0.00000
2  0.000000  0.0  0.000323  0.000000  0.0  0.0  0.0   0.00000
3  0.000000  0.0  0.000000  0.000000  0.0  0.0  0.0   0.00000
4  0.000193  0.0  7.451379  6.552213  0.0  0.0  0.0   0.00000

4:最后,转换为一个列表,并用to_numpytolist重新分配给原始df:

df['class_proba'] = df_proba.to_numpy().tolist()
print (df.head())
                                           words  \
0                          i  havent  been  back   
1                                       but  its   
2              they  used  to  get  more  closer   
3                                        no  way   
4  when  we  have  some  type  of  a  thing  for   

                                         class_proba  
0   [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 10.55798974]  
1           [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]  
2  [0.0, 0.0, 0.00032289312, 0.0, 0.0, 0.0, 0.0, ...  
3           [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]  
4  [0.000193199, 0.0, 7.451379, 6.552212946999999...  

【讨论】:

  • 这太神奇了,谢谢。它不仅解决了我的问题,而且使优化更容易实现。
  • @connor449 很高兴它有帮助 :) 我在输入上做了一些计时,它几乎快了两倍,但如果你将 df 的大小增加 10 倍,那么它会快 14 倍以上!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-01
  • 1970-01-01
相关资源
最近更新 更多