假设我有一个NumPy数组a:
a = np.array([ [1, 2, 3], [2, 3, 4] ])
我想添加一列零以获取一个数组b:
b = np.array([ [1, 2, 3, 0], [2, 3, 4, 0] ])
我如何在NumPy中轻松地做到这一点?
我认为,更简单,更快速的启动方法是执行以下操作:
import numpy as np N = 10 a = np.random.rand(N,N) b = np.zeros((N,N+1)) b[:,:-1] = a
和时间:
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