如果我从一个 3x4 数组开始,然后将一个 3x1 数组与轴 1 连接起来,我将得到一个 3x5 数组:
In [911]: x = np.arange(12).reshape(3,4)
In [912]: np.concatenate([x,x[:,-1:]], axis=1)
Out[912]:
array([[ 0, 1, 2, 3, 3],
[ 4, 5, 6, 7, 7],
[ 8, 9, 10, 11, 11]])
In [913]: x.shape,x[:,-1:].shape
Out[913]: ((3, 4), (3, 1))
请注意,要连接的两个输入都有 2 个维度。
省略:,x[:,-1] 是 (3,) 形状 - 它是 1d,因此错误:
In [914]: np.concatenate([x,x[:,-1]], axis=1)
...
ValueError: all the input arrays must have same number of dimensions
np.append 的代码是(在这种情况下指定了轴)
return concatenate((arr, values), axis=axis)
所以只要稍微改变语法append 就可以了。它需要 2 个参数,而不是一个列表。它模仿列表append 是语法,但不应与该列表方法混淆。
In [916]: np.append(x, x[:,-1:], axis=1)
Out[916]:
array([[ 0, 1, 2, 3, 3],
[ 4, 5, 6, 7, 7],
[ 8, 9, 10, 11, 11]])
np.hstack 首先确保所有输入都是atleast_1d,然后进行连接:
return np.concatenate([np.atleast_1d(a) for a in arrs], 1)
所以它需要相同的x[:,-1:] 输入。基本相同的操作。
np.column_stack 也在轴 1 上进行连接。但首先它通过 1d 输入
array(arr, copy=False, subok=True, ndmin=2).T
这是将 (3,) 数组转换为 (3,1) 数组的一般方法。
In [922]: np.array(x[:,-1], copy=False, subok=True, ndmin=2).T
Out[922]:
array([[ 3],
[ 7],
[11]])
In [923]: np.column_stack([x,x[:,-1]])
Out[923]:
array([[ 0, 1, 2, 3, 3],
[ 4, 5, 6, 7, 7],
[ 8, 9, 10, 11, 11]])
所有这些“堆栈”都很方便,但从长远来看,了解尺寸和基础np.concatenate 很重要。还知道如何查找此类函数的代码。我经常使用ipython ?? 魔法。
在时间测试中,np.concatenate 明显更快 - 对于这样的小数组,额外的函数调用层会产生很大的时间差异。