I’m currently struggling with a probably rather simple question but I can’t get my head around it.
Assuming I have the follow two 2d arrays with different shapes, I can combine them into a new array using:
a = np.zeros((2, 3)) b = np.zeros((4, 5)) c = np.array([a, b]) print(c.shape) # Output # (2,) for elements in c: print(elements.shape) # Output: # (2, 3) # (4, 5)
So far so good! But how would I do this if I have a large list where I’d have to iterate over? Here is a simple example with just 4 different 2d arrays:
This works as expected:
a = np.zeros((2,3)) b = np.zeros((4,5)) c = np.zeros((6,7)) d = np.zeros((8,9)) e = np.array([a, b, c, d]) print(e.shape) # Output # (4,) for elements in e: print(elements.shape) # Output # (2, 3) # (4, 5) # (6, 7) # (8, 9)
This doesn’t work as expected and my question would be how to do this in an iterative way:
a = np.zeros((2,3)) b = np.zeros((4,5)) c = np.zeros((6,7)) d = np.zeros((8,9)) e = None for elements in [a, b, c, d]: e = np.array([e, elements]) print(e.shape) # Output # (2,) <--- This should be (4,) as in the upper example, but I don't know how to achieve that :-/ for elements in e: print(elements.shape) # (2,) # (8, 9)
I understand that in each iteration I’m just combining two arrays why it always stays at shape of (2,), but I wonder how this can be done in an elegant way. So basically I want to have a third dimension which states the count or amount of arrays that are stored. E.g. if I iterate of 1000 different 2d arrays I’d expect to have a shape of (1000,)
Hope my question is understandable – if not let me know! Thanks a lot!
Advertisement
Answer
If I understood your issue correctly, you can achieve what you want in a list comprehension. This will yield the exact same solution as your code above that you described as working.
a = np.zeros((2,3)) b = np.zeros((4,5)) c = np.zeros((6,7)) d = np.zeros((8,9)) e = np.array([element for element in [a, b, c, d]]) print(e.shape) for elements in e: print(elements.shape)