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

2 Answers 2

9

Try with np.column_stack:

d = np.column_stack([a, b, c])
Sign up to request clarification or add additional context in comments.

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

2 Comments

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

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.