2016-08-09 58 views
4

我遇到np.append问题。ValueError:所有输入数组必须具有相同的维数

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

所以尺寸匹配?错误在哪里?

+5

尝试'np.column_stack'。 – Divakar

+2

它的工作!但为什么? – odo22

回答

5

如果我和3×4阵列开始,并连接一个3×1阵列,其中轴1,得到了一个3×5阵列:

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,)形状 - 这是一维,并因此错误:

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.一个串连但首先通过它

array(arr, copy=False, subok=True, ndmin=2).T 

通过1D输入本是转动该(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是很重要的。也知道如何查找这样的函数的代码。我使用了很多魔术。

而在时间测试中,np.concatenate明显更快 - 这样一个小型数组,多余的函数调用层次会产生很大的时间差异。

3

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

2

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

'np.append'比列表'.append'慢;但与“堆栈”相当。它使用'np.concatenate'。 – hpaulj

+0

@hpaulj所以...正如我所说的使用'append' vs'stack'与2个矩阵相同,'stack'对于超过2个元素是更好的,所以'stack'总是_至少与'append'一样好'。 – RuRo

相关问题