-1

I have the following array:

x_train.shape
(7201,)

x_train
array([array([[0.01709922],
       [0.01946028],
       [0.01317027],
       [0.01228488],
       [0.01372365],
       [0.02148931],
       [0.01127036],
       [0.01887001],
       [0.01468282],
       [0.01235866]], dtype=float32),
       array([[0.01269068],
       [0.01193441],
       [0.01077232],
       [0.01219265],
       [0.02014277],
       [0.01250623],
       [0.01759726],
       [0.01145482],
       [0.00204748],
       [0.00372604]], dtype=float32),
       array([[0.01660118],
       [0.01931271],
       [0.02100972],
       [0.0167303 ],
       [0.02126796],
       [0.01245089],
       [0.00612399],
       [0.01128881],
       [0.01344696],
       [0.01422168]], dtype=float32),
       ...,

I want to transform it into the shape (X,10,1).

How can i do this in the first place, whats an efficient way to do this?

2
  • another dup: stackoverflow.com/questions/50971123/… Commented Aug 23, 2022 at 13:24
  • Do you understand why it is a 1d object dtype array in the first place? Are the arrays all the same shape? A quick count suggested that one has 11 rows. If they do match, np.stack(x_train) should work. Commented Aug 23, 2022 at 15:21

1 Answer 1

0

Normally when you instantiate a numpy array using np.array, it will detect if the inputs comprise a regularly shaped array, and if so, it will give you a multi-dimensional array automatically.

If you have somehow managed to end up with an array of objects despite it being regularly shaped, you could convert it to a list and try again, for example:

import numpy as np

x = np.zeros(3, dtype=object)

x[0] = np.array([[1],[2],[3],[4]])
x[1] = np.array([[5],[6],[7],[8]])
x[2] = np.array([[9],[10],[11],[12]])

print(x.shape, x.dtype)  # prints (3,) object                                                                                               

y = np.array(list(x))

print(y.shape, y.dtype) )  # prints (3, 4, 1) int64                                                                                         

If this fails (giving you a warning about ragged sequences) and gives you back another object array, then your array was not in fact regularly shaped - in which case, check the number of elements in each of the subarrays. You will see this if you remove one of the elements in the above test code.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, however this didnt work for me. i found this answer which worked: stackoverflow.com/a/35193026/8055893

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.