简体   繁体   English

numpy数组:有效分配值

[英]Numpy array: efficiently assign values

I have an array and I want to loop through its values to update it as follows: 我有一个数组,我想遍历它的值来更新它,如下所示:

import numpy as np
arr=np.ones((5,7))
for i in range(1,arr.shape[0]-1):
    for j in range(1,arr.shape[1]-1):
        arr[i,j]=arr[i+1,j]+arr[i,j+1]

The result is, as desired, 结果是根据需要,

[[1. 1. 1. 1. 1. 1. 1.]
 [1. 2. 2. 2. 2. 2. 1.]
 [1. 2. 2. 2. 2. 2. 1.]
 [1. 2. 2. 2. 2. 2. 1.]
 [1. 1. 1. 1. 1. 1. 1.]]

However, for-loops are quite slow and I'd like to know if there is a way to make this more efficient. 但是,for循环非常慢,我想知道是否有一种方法可以使这种方法更有效。

Edit: The input is not always np.ones((5,7)) , it will be something more heterogeneous in general. 编辑:输入并不总是np.ones((5,7)) ,一般来说它会更加异构。

If you draw a box around the "inner" elements, your code is setting the new value of those elements to be the sum of (a) that box "shifted one row down", and (b) that box "shifted one column to the right". 如果您在“内部”元素周围绘制一个框,则您的代码会将这些元素的新值设置为(a)框“向下移动一行”和(b)框“向右移动一列”的总和。正确的”。

For example: 例如:

-----     -----     -----
-XXX-     -----     --XXX
-XXX-  =  -XXX-  +  --XXX
-XXX-     -XXX-     --XXX
-----     -XXX-     -----

And you can do that without loops as follows: 您可以如下进行无循环操作:

arr[1:-1,1:-1] = arr[2:,1:-1] + arr[1:-1,2:]

Here is the code for question. 这是有问题的代码。

import numpy as np 
a=np.random.randn(5, 7)
a1=a
a2=a
mid_mat= a[1:, :][:, :-1]+a[:, :-1][:-1, :]
a1[1:-1, 1:-1] = mid_mat[:-1, :-1]

# Assert Code

for i in range(1,a.shape[0]-1):
    for j in range(1,a.shape[1]-1):
        a2[i,j]=a[i+1,j]+a[i,j+1]

np.testing.assert_array_equal(a1, a2)

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

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