Fraz - 3 months ago 31

Python Question

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?

Answer

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
```