Numpy 2d and 1d addition

When using the example from the NumPy Book when starting with NumPy, I noticed an example:

a = zeros((4, 5))
b = ones(6)
add(b, b, a[1:3, 0:3].flat)
print(a)

returns

array([[0, 0, 0, 0, 0]
       [2, 2, 2, 0, 0]
       [2, 2, 2, 0, 0]
       [0, 0, 0, 0, 0]])

However, when I try to execute this code, this results in the following error:

add (b, b, a [1: 3, 0: 3] .flat)

TypeError: returned arrays must be from ArrayType "

Can anyone shed some light on this issue?

+4
source share
1 answer

If you have 2 arguments for numpy.add, they are taken as two operands which added. If you give 3 arguments, then the first two are added, and the third is result. Actually, not the result, but the array in which the result should be stored.

, b b a[1:3, 0:3].flat.

np.add(b, b),

import numpy as np
a = np.zeros((4, 5))
b = np.ones(6)
np.add(b, b)
# returns array([ 2.,  2.,  2.,  2.,  2.,  2.])

, a[1:3, 0:3].flat, <numpy.flatiter at 0x22204e80c10>. , iterator, . , . ravel(). a[1:3, 0:3].ravel() :

array([ 0.,  0.,  0.,  0.,  0.,  0.])

. ( !). :

np.add(b, b, a[1:3, 0:3].ravel())
# array([ 2.,  2.,  2.,  2.,  2.,  2.])

, a:

a
#array([[ 0.,  0.,  0.,  0.,  0.],
#       [ 0.,  0.,  0.,  0.,  0.],
#       [ 0.,  0.,  0.,  0.,  0.],
#       [ 0.,  0.,  0.,  0.,  0.]])

, a . , ravel() ( ), , . , out , . , , , , .

, out , np.add a:

a[1:3, 0:3] = np.add(b, b).reshape(2,3) # You need to reshape here!
a
#array([[ 0.,  0.,  0.,  0.,  0.],
#       [ 2.,  2.,  2.,  0.,  0.],
#       [ 2.,  2.,  2.,  0.,  0.],
#       [ 0.,  0.,  0.,  0.,  0.]])

a[1:3, 0:3].flat = np.add(b, b).

, , numpy, , ​​.

+3

Source: https://habr.com/ru/post/1628678/


All Articles