简体   繁体   English

填充Numpy数组的有效方法

[英]Efficient way to fill Numpy Array

I'm looking for a more efficient way to fill a 2d numpy array than a double for-loop. 我正在寻找一种比双for循环更有效的方法来填充2d numpy数组。 The issue I am having is that the array values are dependent on several other arrays. 我遇到的问题是数组值依赖于其他几个数组。

In the following code k and d are integers, and y and result are arrays. 在以下代码中,k和d是整数,y和result是数组。 Any help would be greatly appreciated. 任何帮助将不胜感激。

for i in xrange(1,d):
    for j in xrange(k-i-1, k+1):
        result[j][i] = ((x - y[j])/(y[j+i] - y[j]))*result[j,i-1] + ((y[j+i+1]-x)/(y[j+i+1] - y[j+1]))*result[j+1,i-1]

You seem to be updating your result array one column at a time, using data from the previously updated column. 您似乎正在使用以前更新的列中的数据一次更新result数组。 That makes it hard to vectorize the outer loop, I don't think you can do it unless there is some structure to your data that can be exploited. 这使得很难对外部循环进行矢量化,除非您的数据中存在可以利用的结构,否则我认为您无法做到。 The inner loop is very straightforward to vectorize: 内部循环非常容易向量化:

for i in xrange(1, d):
    j = np.arange(k-i-1, k+1)
    result[j, i] = ((x - y[j]) / (y[j+i] - y[j]) * result[j, i-1] +
                    (y[j+i+1] - x) / (y[j+i+1] - y[j+1]) * result[j+1, i-1])

There is some marginal improvement you could get by defining a base_j = np.arange(kd-2, k+1) array outside the loop, and then slicing it inside the loop with something like j = base_j[d-i+1:] . 通过在循环外定义base_j = np.arange(kd-2, k+1)数组,然后在循环内使用j = base_j[d-i+1:]对其进行切片,可以得到一些边际改进j = base_j[d-i+1:]

You can get rid of the inner loop via clever broadcasting 您可以通过巧妙的广播摆脱内循环

tmp = ((x - y[k-i+1:k+1])/(y[k+1:k+1+i] - y[j]))*result[k-i+1:k+1,i-1] + ((y[k+2:k+i+2]-x)/(y[k+2:k+i+2] - y[k-i+2:k+2]))*result[k-i+2:k+2,i-1]
result[k-i+1:k+1, i] = tmp

but because you bounds in the inner loop depend on the outer-loop you can not remove it through broadcasting as well. 但是由于您限制内部循环的范围取决于外部循环,因此您也无法通过广播将其删除。

I used tmp in an overabundance of caution 我过分谨慎地使用了tmp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM