Nikolaij
Nikolaij

Reputation: 321

Appending to numpy array within a loop

I really hope to not have missed something, that had been clarified before, but I couldn't find something here.

The task seems easy, but I fail. I want to continuously append a numpy array to another one while in a for-loop:

step_n = 10
steps = np.empty([step_n,1])

for n in range(step_n):
    step = np.random.choice([-1, 0, 1], size=(1,2))
    #steps.append(step) -> if would be lists, I would do it like that
    a = np.append(steps,step)
    #something will be checked after each n

print(a)

The output should be ofc of type <class 'numpy.ndarray'> and look like:

[[-1.  0.]
 [ 0.  0.]
 [-1. -1.]
 [ 1. -1.]
 [ 1.  1.]
 [ 0. -1.]
 [-1.  1.]
 [-1.  0.]
 [ 0. -1.]
 [ 1.  1.]]

However the code fails for some (most probably obvious) reasons. Can someone give me a hint?

Upvotes: 7

Views: 62907

Answers (1)

Felipe Trenk
Felipe Trenk

Reputation: 351

import numpy as np

step_n = 10
steps = np.random.choice([-1, 0, 1], size=(1,2))
for n in range(step_n-1):
    step = np.random.choice([-1, 0, 1], size=(1,2))
    print(steps)
    steps = np.append(steps, step, axis=0)
    #something will be checked after each n

print(steps)

One of the problems is that your steps variable that is initialized outside the for loop has a different size than each step inside. I changed how you initialized the variable steps, by creating your first step outside of the for loop. This way, your steps variable already has the matching size. But notice you need to reduce 1 iteration in the for loop because of this.

Also, you want to update the steps variable in each for loop, and not create a new variable "a" inside it. In your code, you would just end up with the steps array (that never changes) and only the last step.

Upvotes: 9

Related Questions