【发布时间】:2020-06-21 15:09:22
【问题描述】:
基本上,我有一个函数,对于每一行,一次将一个额外的值相加,直到总和达到给定阈值。一旦达到给定的阈值,它就会获取生成的切片索引并使用它来返回另一列的该切片的平均值。
import numpy as np
#Random data:
values = np.random.uniform(0,10,300000)
values2 = np.random.uniform(0,10,300000)
output = [0]*len(values)
#Function that operates one one single row and returns the mean
def function(threshold,row):
slice_sum=0
i=1
while slice_sum < threshold:
slice_sum = values[row-i:row].sum()
i=i+1
mean = values2[row-i:row].mean()
return mean
#Loop to iterate the function row by row:
for i in range(15,len(values)): #let's just skip the first 15 values, otherwise the loop might get stuck. This issue is not prioritary though.
output[i] = function(40,i)
这是循环的简化版本。它可能看起来并不慢,但从所有意图和实际目的来看,它都非常慢。所以我想知道是否有更快的方法可以在没有 for 循环的情况下实现这一目标。
谢谢
【问题讨论】:
-
只是为了简化问题,您不需要预先分配
output到任何特定长度。只需使用output = [function(40, i) for i in range(15, len(values))]。
标签: python numpy loops iteration