6

I have 3 vectors like the following:

a = np.ones(20) b = np.zeros(20) c = np.ones(20) 

I am trying to combine them into one matrix of dimension 20x3.

Currently I am doing:

n1 = np.vstack((a,b)) n2 = np.vstack((n1,c)).T 

This works, but isn't there a way to fill matrix with arrays in column-wise fashion?

2 Answers 2

15

There are a few different ways you could do this. Here are a some examples:

Using np.c_:

np.c_[a, b, c] 

Using np.dstack and np.squeeze:

np.dstack((a, b, c)).squeeze() 

Using np.vstack and transpose (similar to your method):

np.vstack((a,b,c)).T 

Using np.concatenate and reshape:

np.concatenate((a, b, c)).reshape((-1, 3), order='F') 

If efficiency matters here, the last method using np.concatenate appears to be by far the quickest on my computer:

>>> %timeit np.c_[a, b, c] 10000 loops, best of 3: 46.7 us per loop >>> %timeit np.dstack((a, b, c)).squeeze() 100000 loops, best of 3: 18.2 us per loop >>> %timeit np.vstack((a,b,c)).T 100000 loops, best of 3: 17.8 us per loop >>> %timeit np.concatenate((a, b, c)).reshape((-1, 3), order='F') 100000 loops, best of 3: 3.41 us per loop 
Sign up to request clarification or add additional context in comments.

Comments

5

Yes, use column_stack:

np.column_stack((a,b,c)) 

That works for stacking general 1-d arrays. In your specific case where you want a 20x3 array such that each row is (1,0,1), I'd suggest:

np.tile([1.,0.,1.], (20,1)) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.