4

I am learning more about numpy and need help creating an numpy array from multiple lists. Say I have 3 lists,

a = [1, 1, 1] 
b = [2, 2, 2] 
c = [3, 3, 3] 

How can I create a new numpy array with each list as a column? Meaning that the new array would be [[1, 2, 3], [1, 2, 3], [1, 2, 3]]. I know how to do this by looping through the lists but I am not sure if there is an easier way to accomplish this. The numpy concatenate function seems to be close but I couldn't figure out how to get it to do what I'm after. Thanks

sacuL
51.6k9 gold badges88 silver badges115 bronze badges
asked Dec 7, 2018 at 22:07

2 Answers 2

9

Try with np.column_stack:

d = np.column_stack([a, b, c])
answered Dec 7, 2018 at 22:11

Comments

3

No need to use numpy. Python zip does a nice job:

In [606]: a = [1, 1, 1] 
 ...: b = [2, 2, 2] 
 ...: c = [3, 3, 3] 
In [607]: abc = list(zip(a,b,c))
In [608]: abc
Out[608]: [(1, 2, 3), (1, 2, 3), (1, 2, 3)]

But if your heart is set on using numpy, a good way is to make a 2d array, and transpose it:

In [609]: np.array((a,b,c))
Out[609]: 
array([[1, 1, 1],
 [2, 2, 2],
 [3, 3, 3]])
In [610]: np.array((a,b,c)).T
Out[610]: 
array([[1, 2, 3],
 [1, 2, 3],
 [1, 2, 3]])

Others show how to do this with stack and column_stack, but underlying these is a concatenate. In one way or other they turn the lists into 2d arrays that can be joined on axis=1, e.g.

In [616]: np.concatenate([np.array(x)[:,None] for x in [a,b,c]], axis=1)
Out[616]: 
array([[1, 2, 3],
 [1, 2, 3],
 [1, 2, 3]])
answered Dec 8, 2018 at 0:06

2 Comments

Why double parenth?
@stackexchange_account1111, it could also be np.array([a,b,c])

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.