teteh May
teteh May

Reputation: 455

List to Numpy Array and Reshape (Dimension Problem)

I have a list from appending 2 numpy array.

mylist=

[array([[5.45, 2.97, 6.25],
        [7.27, 5.28, 4.18]]),
array([[4.54, 2.06, 2.53],
       [7.2, 5.28, 1.29]])]

I would like to re-create numpy array from this list as follow:

array([[5.45, 2.97, 6.25,4.54, 2.06, 2.53]],
       [7.27, 5.28, 4.18,7.2, 5.28, 1.29]])

I tried np.array(mylist).reshape(2,6), but the result is not as my aim.

Upvotes: 0

Views: 49

Answers (2)

hpaulj
hpaulj

Reputation: 231475

In [145]: alist = [np.array([[5.45, 2.97, 6.25],
     ...:         [7.27, 5.28, 4.18]]),
     ...:         np.array([[4.54, 2.06, 2.53],
     ...:         [7.2, 5.28, 1.29]])]

In [147]: np.hstack(alist)
Out[147]: 
array([[5.45, 2.97, 6.25, 4.54, 2.06, 2.53],
       [7.27, 5.28, 4.18, 7.2 , 5.28, 1.29]])

which is just a compact way of calling

In [148]: np.concatenate(alist, axis=1)
Out[148]: 
array([[5.45, 2.97, 6.25, 4.54, 2.06, 2.53],
       [7.27, 5.28, 4.18, 7.2 , 5.28, 1.29]])

Upvotes: 1

Hammad Ahmed
Hammad Ahmed

Reputation: 885

arr = np.array(mylist)
arr

>>> [[[5.45, 2.97, 6.25],
      [7.27, 5.28, 4.18]],

     [[4.54, 2.06, 2.53],
      [7.2 , 5.28, 1.29]]]

you need to swap the first and second axis before reshaping

brr = arr.transpose([1, 0, 2]).reshape(2, -1)
brr

>>> [[5.45, 2.97, 6.25, 4.54, 2.06, 2.53],
     [7.27, 5.28, 4.18, 7.2 , 5.28, 1.29]]

Upvotes: 1

Related Questions