0

I have

x = np.array([[1, 5], [2, 8]])
x.shape

The shape of x is (2,2)

How do I make new array y, that will contain 40 different arrays of the same shape x? The desired y array should be of dimension (40,2,2)

When I try y = np.expand_dims(x, axis=1) it gives me shape (2, 1, 2). I don't understand how numpy append things in different axes... Thanks!

4
  • Possible duplicate of "Cloning" row or column vectors Commented Dec 21, 2018 at 9:59
  • @MatthieuBrucher thanks for the replay, but I didn't mean a copy from this array, but rather appending different arrays of same shape x. Commented Dec 21, 2018 at 10:06
  • maby np.dstack will help? Commented Dec 21, 2018 at 10:24
  • 1
    @KrzysztofJurkiewicz: Just answered a minute ago :) Commented Dec 21, 2018 at 10:26

3 Answers 3

1

Since you wrote you want an array y of higher dimension, you can simply initialize an array of zeros as

y = np.zeros((40, x.shape[0],x.shape[1]))
print (y.shape)
# (40, 2, 2)

where you provide the size of the array x.

EDIT

Based on your comment below, here is the answer. You can use dstack where you provide the arrays to be stacked as a tuple (x, z) here and it stacks them along the third axis.

x = np.array([[1, 5], [2, 8]])  
z = np.array([[11, 55], [22, 88]]) 
y = np.dstack((x,z))
y.shape
# (2, 2, 2)

EDIT 2

To stack it in the front, you can use swapaxes an swap the first and the third axes.

y = np.dstack((x,z,x)).swapaxes(0,2)
y.shape
# (3, 2, 2)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the replay but the thing is I have already 40 different arrays. But for the sake of simplicity lets say I have 2 different arrays x = np.array([[1, 5], [2, 8]]) and z = np.array([[11, 55], [22, 88]]) . Now I want hew array y of dimesion (2,2,2) that appended this two arrays in the 0 axis
that edit extends the array in its last dimension, see y = np.dstack((x,z,x)) # (2,2,3)
y = np.stack((x, y, z)) is an alternative to the dstack with swap. It takes an axis parameter to give even more control.
0

Try this:

import numpy as np

x = np.array([[1, 5], [2, 8]])

y = np.asanyarray([x] * 40)

print(y.shape)

The output shape would be (40, 2, 2).

Comments

0

It seems that you want to concatenate multiple arrays together in a new dimension:

import numpy as np
x = np.array([[1, 5], [2, 8]])
y = np.array([[11, 55], [22, 88]])

z = np.array([x, y, x])
print(z.shape)  # (3, 2, 2)

1 Comment

Do you really need the tolist()?

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.