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

问题描述 投票:14回答:4

我遇到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:所有输入数组必须具有相同的维数

但是,我通过这样做检查了矩阵尺寸

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

我明白了

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

尺寸是否匹配?哪里出错了?

python arrays numpy append
4个回答
12
投票

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


8
投票

(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)阵列。


5
投票

你得到错误的原因是因为“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


0
投票

您也可以通过括在括号[]中来强制转换(n,)到(n,1)。

例如而不是np.append(b,a,axis=0)使用np.append(b,[a],axis=0)

a=[1,2]
b=[[5,6],[7,8]]
np.append(b,[a],axis=0)

回报

array([[5, 6],
       [7, 8],
       [1, 2]])
© www.soinside.com 2019 - 2024. All rights reserved.