Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 808
Nikolaij Avatar asked May 27 '20 15:05

Nikolaij


People also ask

How do you append an array in a for loop?

Answer: Use the push() Method You can simply use the JavaScript push() method to append values to an array.

Can you append to an array in Python NumPy?

append() is used to append values to the end of an array. It takes in the following arguments: arr : values are attached to a copy of this array.

How do I append an element to an array in NumPy?

Use append() to add an element to Numpy Array. Use concatenate() to add an element to Numpy Array. Use insert() to add an element to Numpy Array.


1 Answers

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.

like image 145
Felipe Trenk Avatar answered Jan 03 '23 13:01

Felipe Trenk