+2 votes
in Programming Languages by (73.8k points)
edited by
I want to create a 2D array using lists. Each list should be a column in the matrix. How can I do that?

I tried numpy's hstack() and append(), but it did not work.

E.g.:

a = [1, 2, 3]

b = [4, 5, 6]

output:

[[1, 4],

 [2, 5],

 [3, 6]]

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

Since you want lists to be columns of the matrix, you need to first reshape the lists and then you can use hstack().

Here is an example:

>>> a
[1, 2, 3]
>>> b
[4, 5, 6]
>>> c
[7, 8, 9]
>>> np.hstack((np.reshape(a, (len(a),1)), np.reshape(b, (len(b),1)), np.reshape(c, (len(c),1))))
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])
 


...