How to add an extra column to a NumPy array

前端 未结 17 2133
一个人的身影
一个人的身影 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:33

    I like JoshAdel's answer because of the focus on performance. A minor performance improvement is to avoid the overhead of initializing with zeros, only to be overwritten. This has a measurable difference when N is large, empty is used instead of zeros, and the column of zeros is written as a separate step:

    In [1]: import numpy as np
    
    In [2]: N = 10000
    
    In [3]: a = np.ones((N,N))
    
    In [4]: %timeit b = np.zeros((a.shape[0],a.shape[1]+1)); b[:,:-1] = a
    1 loops, best of 3: 492 ms per loop
    
    In [5]: %timeit b = np.empty((a.shape[0],a.shape[1]+1)); b[:,:-1] = a; b[:,-1] = np.zeros((a.shape[0],))
    1 loops, best of 3: 407 ms per loop
    

提交回复
热议问题