0

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.

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

12 Comments

I want 1 added to each element of a, and thus form b - if that makes sense..The answer iam looking is b=[[1,2,3],[4,5,6]]
Ionut: Sorry, but I was looking to learn how to iterate over multidimensional arrays - although your solution does work for this situation..
Ionut: Thanks a lot for this! really appreciate this help. I have been trying to look around, but not much luck.
@user2152572 b = a + 1 is the right answer. You don't ever want to iterate over an ndarray because it'll be too slow. Numpy is designed for 'vectorized' calculations: if you use Numpy routines (rather than looping) you'll get the result much quicker.
What poorsod was saying is that using the numpy routines is a lot faster then iterating through the array yourself, but you may do so if it's for learning purposes.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.