2016-11-10 34 views
0

我尝试以下操作:如何在连接两个numpy数组时解决错误?

rands = np.empty((0, 10)) 
rand = np.random.normal(1, 0.1, 10) 
rands = np.concatenate((rands,rand),axis=0) 

使我有以下错误:

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

但是,为什么是这个错误?为什么我不能用这个命令在矩阵rands中追加新行rand

备注:

我可以 '修复' 该使用以下命令:

rands = np.concatenate((rands,rand.reshape(1, 10)),axis=0) 

,但它看起来不再符合Python,但繁琐......

也许有用更少的括号和重新塑造更好的解决方案...?

+0

嘛'虽然有rands'最初的空行仍然是二维的形状是'(0,10)',这就是为什么它是borks – EdChum

+0

是的,一行是一维的10个元素。我不明白这里的问题是什么...... – Alex

+0

不是在numpy的眼睛里,它不是你仍然会得到与'rands = np.empty((1,10))相同的错误' – EdChum

回答

3

rands已成形(0, 10)rand已形状(10,)

In [19]: rands.shape 
Out[19]: (0, 10) 

In [20]: rand.shape 
Out[20]: (10,) 

如果试图沿着0轴拼接,则rands(长度0)0轴的值与的rand(长度10)的0轴。 图示地,它看起来像这样:

兰特:

| | | | | | | | | | | 

兰特:

| | 
| | 
| | 
| | 
| | 
| | 
| | 
| | 
| | 
| | 

两个形状并不完全吻合,因为rands 1轴的长度为10和rand缺少1轴。

要解决此问题,可以促进rand塑造(1, 10)的二维数组:

In [21]: rand[None,:].shape 
Out[21]: (1, 10) 

因此,在rand的10个项目沿一轴正在布局。然后

rands = np.concatenate((rands,rand[None,:]), axis=0) 

返回形状的阵列(1, 10)

In [26]: np.concatenate((rands,rand[None,:]),axis=0).shape 
Out[26]: (1, 10) 

或者,你可以使用row_stack没有促进rand到一个二维数组:

In [28]: np.row_stack((rands,rand)).shape 
Out[28]: (1, 10) 
+0

我喜欢row_stack。现在它看起来更pythonic.Thanks! – Alex

相关问题