Skip to content Skip to sidebar Skip to footer

How To Turn Array Of Array Into Single High Dimension Array?

I have a Python script and somehow in my Numpy calculation I got a variable like this: In [72]: a Out[72]: array([[ array([-0.02134025+0.1445159j , -0.02136137+0.14458584j,

Solution 1:

This behaviour is caused by the complex data type you are using. If you look carefully at your array, you can spot, that the dtype of the inner array is object and not complex as it should be. Please check if this is solved by setting the dtype of the inner arrays properly during the calculation/creation.

If this does not help, please check this SO thread. It's about a similar problem and might offer you an easy solution.

Solution 2:

a is, as noted, a 2d array, where each element is a 1d array.

np.array(...) tries to create as high a dimensional array as it can. But if the subelements (or lists) vary in size it can't, and resorts to making a object array (or in some cases raising an error). Your T1 is this kind of array.

If your subarrays are all the same shape, we can convert it in to a 3d array.

I can't recreate your T4 with a copynpaste because np.array makes a 3d array:

In [35]: array = np.array
In [36]: T4= array([[array([ 0.  ,  0.25,  0.5 ,  0.75,  1.  ]),
    ...:         array([ 0.,  0.,  0.,  0.,  0.])],
    ...:        [array([ 0.,  0.,  0.,  0.,  0.]), array([ 1.,  1.,  1.,  1.,  1
    ...: .])]], dtype=object)
    ...:        
In [37]: T4
Out[37]: 
array([[[0.0, 0.25, 0.5, 0.75, 1.0],
        [0.0, 0.0, 0.0, 0.0, 0.0]],

       [[0.0, 0.0, 0.0, 0.0, 0.0],
        [1.0, 1.0, 1.0, 1.0, 1.0]]], dtype=object)

But with your dot sequence:

In [41]: T1 = np.array([ [np.linspace(0,1,5),0],[0,1] ])
In [42]:  T2 = np.identity(2)
In [43]: T3 = np.dot(T1,T2)
In [44]: T4 = np.dot(T2,T3)

But I can convert it into one array with concatenate. Actually stack is best here. But first I have to turn it into a 1d array (4,). np.vstack would also work. Effectively it is now a list of 4 5-element arrays:

In [47]: np.stack(T4.ravel())
Out[47]: 
array([[ 0.  ,  0.25,  0.5 ,  0.75,  1.  ],
       [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ],
       [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ],
       [ 1.  ,  1.  ,  1.  ,  1.  ,  1.  ]])
In [48]: _.reshape(2,2,-1)
Out[48]: 
array([[[ 0.  ,  0.25,  0.5 ,  0.75,  1.  ],
        [ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ]],

       [[ 0.  ,  0.  ,  0.  ,  0.  ,  0.  ],
        [ 1.  ,  1.  ,  1.  ,  1.  ,  1.  ]]])

Usually I recreate arrays like T4 by making a blank object array, e.g. a = np.zeros((2,2),object), and then filling the slots from a list. But posters also get them from third party packages. So this stack trick is a useful one to know.

Post a Comment for "How To Turn Array Of Array Into Single High Dimension Array?"