How to convert an array of arrays to a multidimensional array in Python?

I have an array of NumPy (lengths X) arrays, all of which are of the same length (Y), but are of type โ€œobjectโ€ and therefore have dimension (X,). I would like to "convert" this to a dimension array (X, Y) with the member type of the member arrays ("float").

The only way I can do this is by hand with something like

[x for x in my_array]

Is there a better idiom for doing this โ€œconversionโ€?


For example, I have something like:

array([array([ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]),
       array([ 0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]),
       array([ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]), ...,
       array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.]),
       array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.]),
       array([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.])], dtype=object)

which has shape(X,), not (X, 10).

+2
source share
1 answer

. :

In [1]: a=np.array([1,2,3],dtype=object)
   ...: b=np.array([4,5,6],dtype=object)

, array, :

In [2]: l=np.array([a,b])
In [3]: l
Out[3]: 
array([[1, 2, 3],
       [4, 5, 6]], dtype=object)
In [4]: l.shape
Out[4]: (2, 3)

:

In [5]: arr = np.empty((2,), object)
In [6]: arr[:]=[a,b]
In [7]: arr
Out[7]: array([array([1, 2, 3], dtype=object), 
               array([4, 5, 6], dtype=object)], 
              dtype=object)

np.stack np.array, concatenate:

In [8]: np.stack(arr)
Out[8]: 
array([[1, 2, 3],
       [4, 5, 6]], dtype=object)
In [9]: _.astype(float)
Out[9]: 
array([[ 1.,  2.,  3.],
       [ 4.,  5.,  6.]])

concatenate, hstack vstack . .

arr 2d ( ), ravel.

+2

Source: https://habr.com/ru/post/1682477/


All Articles