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?
Answer: Use the push() Method You can simply use the JavaScript push() method to append values to an array.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With