gpt4 book ai didi

python - 值错误 : all the input arrays must have same number of dimensions

转载 作者:太空狗 更新时间:2023-10-29 17:03:09 25 4
gpt4 key购买 nike

我在使用 np.append 时遇到问题。

我正在尝试使用以下代码复制 20x361 矩阵 n_list_converted 的最后一列:

n_last = []
n_last = n_list_converted[:, -1]
n_lists = np.append(n_list_converted, n_last, axis=1)

但是我得到错误:

ValueError: all the input arrays must have same number of dimensions

但是,我已经检查了矩阵维度

 print(n_last.shape, type(n_last), n_list_converted.shape, type(n_list_converted))

我明白了

(20L,) (20L, 361L)

所以尺寸匹配?哪里错了?

最佳答案

如果我从一个 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 明显更快 - 对于像这样的小数组,额外的函数调用层会产生很大的时间差异。

关于python - 值错误 : all the input arrays must have same number of dimensions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38848759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com