How to add an extra column to a NumPy array How to add an extra column to a NumPy array python python

# How to add an extra column to a NumPy array

`np.r_[ ... ]` and `np.c_[ ... ]`are useful alternatives to `vstack` and `hstack`,with square brackets [] instead of round ().
A couple of examples:

``: import numpy as np: N = 3: A = np.eye(N): np.c_[ A, np.ones(N) ]              # add a columnarray([[ 1.,  0.,  0.,  1.],       [ 0.,  1.,  0.,  1.],       [ 0.,  0.,  1.,  1.]]): np.c_[ np.ones(N), A, np.ones(N) ]  # or twoarray([[ 1.,  1.,  0.,  0.,  1.],       [ 1.,  0.,  1.,  0.,  1.],       [ 1.,  0.,  0.,  1.,  1.]]): np.r_[ A, [A[1]] ]              # add a rowarray([[ 1.,  0.,  0.],       [ 0.,  1.,  0.],       [ 0.,  0.,  1.],       [ 0.,  1.,  0.]]): # not np.r_[ A, A[1] ]: np.r_[ A[0], 1, 2, 3, A[1] ]    # mix vecs and scalars  array([ 1.,  0.,  0.,  1.,  2.,  3.,  0.,  1.,  0.]): np.r_[ A[0], [1, 2, 3], A[1] ]  # lists  array([ 1.,  0.,  0.,  1.,  2.,  3.,  0.,  1.,  0.]): np.r_[ A[0], (1, 2, 3), A[1] ]  # tuples  array([ 1.,  0.,  0.,  1.,  2.,  3.,  0.,  1.,  0.]): np.r_[ A[0], 1:4, A[1] ]        # same, 1:4 == arange(1,4) == 1,2,3  array([ 1.,  0.,  0.,  1.,  2.,  3.,  0.,  1.,  0.])``

(The reason for square brackets [] instead of round ()is that Python expands e.g. 1:4 in square --the wonders of overloading.)

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

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

And timings:

``In [23]: N = 10In [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 loopIn [27]: %timeit b = np.zeros((a.shape[0],a.shape[1]+1)); b[:,:-1] = a100000 loops, best of 3: 5.62 us per loop``

Use `numpy.append`:

``>>> a = np.array([[1,2,3],[2,3,4]])>>> aarray([[1, 2, 3],       [2, 3, 4]])>>> z = np.zeros((2,1), dtype=int64)>>> zarray([[0],       [0]])>>> np.append(a, z, axis=1)array([[1, 2, 3, 0],       [2, 3, 4, 0]])``