6

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

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

The numpy array I want is:

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

which I can get by typing the individual items from the list directly into the numpy array expression 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 the lists into the desired numpy array.

3 Answers 3

6

One way to do it would be to create your numpy array and then use the transpose function to convert it to your desired output:

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)

Output

[[  2.   18.    2.3]
 [  7.   29.    4.6]
 [  8.   44.    8.9]
 [  5.   33.    7.7]]
Sign up to request clarification or add additional context in comments.

Comments

4

you could use np.transpose directly:

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

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

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

1 Comment

Any for creating a reversed dimensions duplicate transpose
4

also you can use zip function like this

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]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.