I am trying to loop through a set of coordinates and 'stacking' these arrays of coordinates to another array (so in essence I want to have an array of arrays) using numpy.
This is my attempt:
import numpy as np
all_coordinates = np.array([[]])
for y in range(2):
for x in range(2):
coordinate = np.array([[x,y]])
# append
all_coordinates = np.append(all_coordinates,[coordinate])
print(all_coordinates)
But it's not working. It's just concatenating the individual numbers and not appending the array.
Instead of giving me (the output that I want to achieve):
[[0 0] [1 0] [0,1] [1,1]]
The output I get instead is:
[0 0 1 0 0 1 1 1]
Why? What I am doing wrong here?
np.stack([(x, y) for x in range(2) for y in range(2)])may be a suitable option for you. I don't think re-stacking after creating each coordinate will work. If there is a specific reason that does not work for you, concatenate may be a better option.np.appendin loops, this is very inefficient (both space and time). Use a list andnp.concatenate/np.stack/np.hstack/np.vstack. By the way, you can reshape your output:all_coordinates.reshape(-1, 2). In fact, the aforementioned does that internally. Additionally, you can preallocate the array to the right shape directly and assign lines. This is more space-efficient and it should also be faster.