使用不同索引的numpy迭代 [英] Iterating with numpy with different indexes

查看:161
本文介绍了使用不同索引的numpy迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个使用范围的for循环,如下所示。有没有一种方法可以消除for循环并仅使用numpy数组?

Say I have a for loop using range as shown below. Is there a good way to eliminate the for loop and use numpy arrays only?

y =[146, 96, 59, 133, 192, 127, 79, 186, 272, 155, 98, 219]

At=3
Bt=2
Aindex=[]
Bindex=[]
for i in range(len(y)-1):
    A =At
    B =Bt

    At =y[i] / y[i] + 5 * (A + B)
    Aindex.append(At)
    Bt =(At - A) + y[i+1] * B
    Bindex.append(Bt)

我会使用类似

c=len(y)-1
Aindex=y[:c]/y[:c]+5* (A + B)

但A和B在循环中更新。我也不知道如何在Bt方程中对y [i + 1]进行矢量化

But A and B updates in the loop. I also do not know how to vectorize y[i+1] in the Bt equation

推荐答案

你在使用类似枚举函数的numpy数组进行迭代,除了 A B 没有改变。

You asked something similar in Iterating over a numpy array with enumerate like function, except there A and B did not change.

严格来说,你无法对这种情况进行矢量化,因为 BT 。这是一个迭代问题,其中 i + 1 术语取决于 i 术语。大多数 numpy 向量操作一次性(有效地)在所有条款上运行。

Strictly speaking you can't vectorize this case, because of that change in Bt. This an iterative problem, where the i+1 term depends on the i term. Most of the numpy vector operations operate (effectively) on all terms at once.

你能否重新解决问题所以它使用 cumsum 和/或 cumprod ?这些是逐步通过向量(或数组的轴),计算累积和或产品的内置方法。 numpy的这个概括是 ufunc.accumulate

http://docs.scipy.org/doc/numpy/reference/generated/numpy。 ufunc.accumulate.html

Could you rework the problem so it makes use of cumsum and/or cumprod? Those are builtin methods that step through a vector (or axis of an array), calculating a cumulative sum or product. numpy's generalization of this is ufunc.accumulate.
http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.accumulate.html

与此同时,我建议更多地使用数组

In the meantime, I'd suggest making more use of arrays

y = np.array(y)
At = np.zeros(y.shape)
Bt = np.zeros(y.shape)
At[0] = 3
Bt[0] = 2 
for i in range(len(y)-1):
    A, B = At[i],Bt[i]
    At[i+1] =y[i] / y[i] + 5 * (A + B)
    Bt[i+1] =(At[i+1] - A) + y[i+1] * B

numpy 使用 nditer 一起遍历几个数组(包括输出数组)。 http://docs.scipy.org/doc/numpy/reference/ arrays.nditer.html 虽然我怀疑它在处理多维数组时更有用。对于你的1d阵列来说,它可能有点过分。如果速度变得必不可少,你可以通过这个文档,并在 cython 中实现问题。

numpy uses an nditer to step through several array (including an output one) together. http://docs.scipy.org/doc/numpy/reference/arrays.nditer.html Though I suspect it is more useful when working on multidimensional arrays. For your 1d arrays it is probably overkill. Still if speed becomes essential, you could work through this documentation, and implement the problem in cython.

这篇关于使用不同索引的numpy迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆