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!

mitevva_t
  • 139
  • 3
  • 12

3 Answers3

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)
Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • 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 – mitevva_t Dec 21 '18 at 10:18
  • that edit extends the array in its last dimension, see y = np.dstack((x,z,x)) # (2,2,3) – Jirka Dec 21 '18 at 10:38
  • `y = np.stack((x, y, z))` is an alternative to the `dstack` with `swap`. It takes an axis parameter to give even more control. – hpaulj Dec 21 '18 at 17:38
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).

Dude
  • 249
  • 2
  • 8
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)
Jirka
  • 1,126
  • 6
  • 25