ValueError:所有输入数组的维数必须相同

2024-03-28 08:47:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我对np.append有问题。

我试图使用下面的代码复制20x361 matrixn_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)

尺寸匹配吗?哪里出错了?


Tags: the代码inputtypenpalllistslist
3条回答

得到错误的原因是因为“1乘n”矩阵不同于长度为n的数组

我建议改用hstack()vstack()。 像这样:

import numpy as np
a = np.arange(32).reshape(4,8) # 4 rows 8 columns matrix.
b = a[:,-1:]                    # last column of that matrix.

result = np.hstack((a,b))       # stack them horizontally like this:
#array([[ 0,  1,  2,  3,  4,  5,  6,  7,  7],
#       [ 8,  9, 10, 11, 12, 13, 14, 15, 15],
#       [16, 17, 18, 19, 20, 21, 22, 23, 23],
#       [24, 25, 26, 27, 28, 29, 30, 31, 31]])

注意重复的“7,15,23,31”栏。 另外,请注意,我使用了a[:,-1:],而不是a[:,-1]。我的版本生成一个列:

array([[7],
       [15],
       [23],
       [31]])

而不是一行array([7,15,23,31])


编辑:append()要慢得多。阅读this answer

(n,)和(n,1)不是同一形状。尝试使用[:, None]符号将向量转换为数组:

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

或者,在提取n_last时,可以使用

n_last = n_list_converted[:, -1:]

获取(20, 1)数组。

如果我从一个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))

注意,要连接的两个输入都有两个维度。

省略:,并且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的代码是(在这种情况下,指定了axis)

return concatenate((arr, values), axis=axis)

所以只要稍微改变一下语法append就行了。它需要两个参数而不是一个列表。它模仿listappend是语法,但不应与list方法混淆。

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的速度明显更快-使用这样的小数组,函数调用的额外层会产生很大的时间差异。

相关问题 更多 >