user2152572
user2152572

Reputation: 47

numpy iterating over multidimensional array

I am very new to numpy and I am trying to achieve the following in the most pythonic way. So, I have two arrays:

a=array([[0, 1, 2],[3,4,5]])
b=zeros(a.shape)

Now, what I would like is for each element in b for be one greater than the value of the corresponding element in a i.e b=a+1

I was wondering how this can be achieved in numpy.

Upvotes: 0

Views: 1166

Answers (1)

Ionut Hulub
Ionut Hulub

Reputation: 6326

The easiest way is the following:

b = a + 1

But if you want to iterate over the array yourself (although not recommended):

for i in range(len(a)):
    for j in range(len(a[i])):
        b[i][j] = a[i][j] + 1

Upvotes: 3

Related Questions