How to add an extra column to a NumPy array

前端 未结 17 2070
一个人的身影
一个人的身影 2020-11-22 14:37

Let’s say I have a NumPy array, a:

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

And I would like to add a column of ze

17条回答
  •  遇见更好的自我
    2020-11-22 15:27

    I find the following most elegant:

    b = np.insert(a, 3, values=0, axis=1) # Insert values before column 3
    

    An advantage of insert is that it also allows you to insert columns (or rows) at other places inside the array. Also instead of inserting a single value you can easily insert a whole vector, for instance duplicate the last column:

    b = np.insert(a, insert_index, values=a[:,2], axis=1)
    

    Which leads to:

    array([[1, 2, 3, 3],
           [2, 3, 4, 4]])
    

    For the timing, insert might be slower than JoshAdel's solution:

    In [1]: N = 10
    
    In [2]: a = np.random.rand(N,N)
    
    In [3]: %timeit b = np.hstack((a, np.zeros((a.shape[0], 1))))
    100000 loops, best of 3: 7.5 µs per loop
    
    In [4]: %timeit b = np.zeros((a.shape[0], a.shape[1]+1)); b[:,:-1] = a
    100000 loops, best of 3: 2.17 µs per loop
    
    In [5]: %timeit b = np.insert(a, 3, values=0, axis=1)
    100000 loops, best of 3: 10.2 µs per loop
    

提交回复
热议问题