给定以下二维数组:
a = np.array([
[1, 2, 3],
[2, 3, 4],
])
我想在第二轴上加上一列0,得到:
b = np.array([
[1, 2, 3, 0],
[2, 3, 4, 0],
])
给定以下二维数组:
a = np.array([
[1, 2, 3],
[2, 3, 4],
])
我想在第二轴上加上一列0,得到:
b = np.array([
[1, 2, 3, 0],
[2, 3, 4, 0],
])
当前回答
我觉得下面这些最优雅:
b = np.insert(a, 3, values=0, axis=1) # Insert values before column 3
插入的一个优点是它还允许您在数组中的其他位置插入列(或行)。此外,您可以轻松地插入整个向量,而不是插入单个值,例如复制最后一列:
b = np.insert(a, insert_index, values=a[:,2], axis=1)
这就导致:
array([[1, 2, 3, 3],
[2, 3, 4, 4]])
对于时间,insert可能比JoshAdel的解决方案慢:
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
其他回答
我认为一个更直接的解决方案和更快的启动是做以下工作:
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
我认为:
np.column_stack((a, zeros(shape(a)[0])))
更优雅。
假设M是一个(100,3)ndarray, y是一个(100,)ndarray追加可以这样使用:
M=numpy.append(M,y[:,None],1)
诀窍在于使用
y[:, None]
这将y转换为(100,1)2D数组。
M.shape
现在给
(100, 4)
我喜欢JoshAdel的回答,因为他关注的是表现。一个较小的性能改进是避免使用零进行初始化的开销,而这些初始化只会被覆盖。当N很大时,这有一个可测量的差异,用空代替零,零的列被写成一个单独的步骤:
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
使用hstack的一种方法是:
b = np.hstack((a, np.zeros((a.shape[0], 1), dtype=a.dtype)))