-1

I accidentally used np.vstack(x) instead of np.stack(x, axis=0). Is there a way to reshape that resulting array from vstack into the regular stack(x, axis=0)?

I have the resulting .npy saved on my computer, so if this is possible you just saved me 6 hours of rerunning my code.

Background:

I have 1501 images of size (250,250) that was incorrectly vstacked. The current array shape of these images + features is (375250, 2048). I would like this array to be (1501, any number). This is why 375250/250 = 1501.

Each array, before stacking, has shape (2048, )

Katsu
  • 8,479
  • 3
  • 15
  • 16
  • What's the current array shape and what shape do you want it to become? I'm a bit confused, sorry. – AJH Apr 11 '22 at 15:39
  • Updated the background information above! – Katsu Apr 11 '22 at 15:42
  • I would expect a `vstack` of a list of (250,250) images to produce a (375250,250) array. I don't know where the `2048` is coming from. It's not a multiple of 250. A `stack` would produce a (1501, 250, 250). – hpaulj Apr 11 '22 at 16:10
  • Each array, before stacking, has shape (2048, ) – Katsu Apr 11 '22 at 16:55

2 Answers2

1

My computer crashed because of not enough RAM to create an array that big, but theoretically, the following should work:

elements = arr.shape[0] * arr.shape[1]
new_col_num = elements//1501

arr2 = arr.reshape(1501, new_col_num)

arr is the array of size (375250, 2048) and arr2 is the array with shape (1501, some number).

AJH
  • 799
  • 1
  • 3
  • 16
0

Reshape should be enough, since your intended axis is the first

To illustrate - with a 3d array pretending to be a list of 2 2d arrays:

In [77]: arr = np.arange(24).reshape(2,3,4)
In [78]: np.stack(arr, 0)
Out[78]: 
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
In [79]: np.vstack(arr)
Out[79]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19],
       [20, 21, 22, 23]])
In [80]: np.vstack(arr).reshape(2,3,4)
Out[80]: 
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
hpaulj
  • 221,503
  • 14
  • 230
  • 353