Python - Conversion of list of arrays to 2D array Python - Conversion of list of arrays to 2D array numpy numpy

# Python - Conversion of list of arrays to 2D array

Not sure if I understood the question correctly, but does this work for you?

``import numpy as npA = [[1,2,3],[4,5,6],[7,8,9]]A = np.array(A)``

If `A` is a list of numpy array, how about this:

``Ah = np.vstack(A)Av = np.hstack(A)``

If I understood correctly what you're asking, you have a case where numpy did not convert array of arrays into 2d array. This can happen when your arrays are not of the same size. Example:

Automatic conversion to 2d array:

``import numpy as npa = np.array([np.array([1,2,3]),np.array([2,3,4]),np.array([6,7,8])])print a``

Output:

``>>>[[1 2 3]    [2 3 4]    [6 7 8]]``

No automatic conversion (look for the change in the second subarray):

``import numpy as npb = np.array([np.array([1,2,3]),np.array([2,3,4,5]),np.array([6,7,8])])print b``

Output:

``>>>[array([1, 2, 3]) array([2, 3, 4, 5]) array([6, 7, 8])]``

I found a couple of ways of converting an array of arrays to 2d array. In any case you need to get rid of subarrays which have different size. So you will need a mask to select only "good" subarrays. Then you can use this mask with list comprehensions to recreate array, like this:

``import numpy as npa = np.array([np.array([1,2,3]),np.array([2,3,4,5]),np.array([6,7,8])])mask = np.array([True, False, True])c = np.array([element for (i,element) in enumerate(a) if mask[i]])print aprint c``

Output:

``>>>>[array([1, 2, 3]) array([2, 3, 4, 5]) array([6, 7, 8])]>>>>[[1 2 3]     [6 7 8]]``

Or you can delete "bad" subarrays and use vstack(), like this:

``import numpy as npa = np.array([np.array([1,2,3]),np.array([2,3,4,5]),np.array([6,7,8])])mask = np.array([True, False, True])d = np.delete(a,np.where(mask==False))e = np.vstack(d)print aprint e``

Output:

``>>>>[array([1, 2, 3]) array([2, 3, 4, 5]) array([6, 7, 8])]>>>>[[1 2 3]     [6 7 8]]``

I believe second method would be faster for large arrays, but I haven't tested the timing.

I think like:

``A = map(lambda t: list(t), A)``