我有一个问题np.append
。
我正在尝试n_list_converted
通过使用以下代码来复制20x361矩阵的最后一列:
n_last = []
n_last = n_list_converted[:, -1]
n_lists = np.append(n_list_converted, n_last, axis=1)
但是我得到了错误:
ValueError:所有输入数组的维数必须相同
但是,我已经通过检查矩阵尺寸
print(n_last.shape, type(n_last), n_list_converted.shape, type(n_list_converted))
我得到
(20公升)(20公升,361公升)
尺寸匹配吗?错误在哪里?
如果我从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
速度明显更快-像这样的小数组,额外的函数调用层会产生很大的时差。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句