Peter Smit - 3 months ago 35

Python Question

Lets say I have an numpy array a:

`a = np.array([[1,2,3],[2,3,4]])`

And I would like to add a column of zeros to get array b:

`b = np.array([[1,2,3,0],[2,3,4,0]])`

How can I do this easily in numpy?

Answer

I think a more straightforward solution and faster to boot is to do the following:

```
import numpy as np
N = 10
a = np.random.rand(N,N)
b = np.zeros((N,N+1))
b[:,:-1] = a
```

And timings:

```
In [23]: N = 10
In [24]: a = np.random.rand(N,N)
In [25]: %timeit b = np.hstack((a,np.zeros((a.shape[0],1))))
10000 loops, best of 3: 19.6 us per loop
In [27]: %timeit b = np.zeros((a.shape[0],a.shape[1]+1)); b[:,:-1] = a
100000 loops, best of 3: 5.62 us per loop
```