7

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?

0

1 Answer 1

9
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! At least creating "a" inside was stupid as hell.
@F. Trenk, how can I do this when generating data inside for-loop? For example, a = np.empty() for-loop a=np.append(a, b)

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.