Convert Python lists to numpy 2D array

I have some lists that I want to convert to a 2D numpy array.

list1 = [ 2, 7 , 8 , 5]
list2 = [18 ,29, 44,33]
list3 = [2.3, 4.6, 8.9, 7.7]

I need a numpy array:

[[  2.   18.    2.3]
 [  7.   29.    4.6]
 [  8.   44.    8.9]
 [  5.   33.    7.7]]

which I can get by typing the individual elements from the list directly into the expression of the numpy array as np.array(([2,18,2.3], [7,29, 4.6], [8,44,8.9], [5,33,7.7]), dtype=float).

But I want to be able to convert lists to the desired numpy array.

+4
source share
3 answers

you can directly use np.transpose:

np.transpose([list1, list2, list3])

and this will convert the list of your lists into a numpy array and wrap it (change rows to columns and columns to rows):

array([[  2. ,  18. ,   2.3],
       [  7. ,  29. ,   4.6],
       [  8. ,  44. ,   8.9],
       [  5. ,  33. ,   7.7]])
+2
source

- numpy, , :

import numpy as np

list1 = [ 2, 7 , 8 , 5]
list2 = [18 ,29, 44,33]
list3 = [2.3, 4.6, 8.9, 7.7]

arr = np.array([list1, list2, list3])
arr = arr.T
print(arr)

[[  2.   18.    2.3]
 [  7.   29.    4.6]
 [  8.   44.    8.9]
 [  5.   33.    7.7]]
+4

zip,

In [1]: import numpy as np

In [2]: list1 = [ 2, 7 , 8 , 5]

In [3]: list2 = [18 ,29, 44,33]

In [4]: list3 = [2.3, 4.6, 8.9, 7.7]

In [5]: np.array(zip(list1,list2,list3))
Out[5]: 
array([[  2. ,  18. ,   2.3],
       [  7. ,  29. ,   4.6],
       [  8. ,  44. ,   8.9],
       [  5. ,  33. ,   7.7]])
+3
source

All Articles