Fix Python – How do I add an extra column to a NumPy array?

Question

Asked By – Peter Smit

Given the following 2D array:

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

I want to add a column of zeros along the second axis to get:

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

Now we will see solution for issue: How do I add an extra column to a NumPy array?


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

This question is answered By – JoshAdel

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0