python 中的数组堆叠/串联错误
Array stacking/ concatenation error in python
我正在尝试连接两个数组:a 和 b,其中
a.shape
(1460,10)
b.shape
(1460,)
我尝试使用 hstack 并连接为:
np.hstack((a,b))
c=np.concatenate(a,b,0)
我被错误困住了
ValueError: all the input arrays must have same number of dimensions
请指导我连接和生成尺寸为 1460 x 11 的数组 c。
np.c_[a, b]
沿最后一个轴连接。
每 the docs、
... arrays will be stacked along their last axis after
being upgraded to at least 2-D with 1's post-pended to the shape
由于 b
的形状为 (1460,)
,其形状在沿最后一个轴连接之前升级为 (1460, 1)
。
In [26]: c = np.c_[a,b]
In [27]: c.shape
Out[27]: (1460, 11)
尝试
b = np.expand_dims( b,axis=1 )
然后
np.hstack((a,b))
或
np.concatenate( (a,b) , axis=1)
将正常工作。
最基本的操作是:
np.concatenate((a,b[:,None]),axis=1)
[:,None]
位将 b
转换为 (1060,1)
数组。现在两个数组的第一个维度匹配,你可以很容易地连接第二个。
b
中添加第 2 维的方法有很多种,例如 reshape
和 expanddims
。 hstack
使用 atleast_1d
在这种情况下没有帮助。 atleast_2d
在错误的一侧添加了 None
。我强烈提倡学习 [:,None]
语法。
一旦数组都是二维的并且在正确的维度上匹配,连接就很容易了。
我正在尝试连接两个数组:a 和 b,其中
a.shape
(1460,10)
b.shape
(1460,)
我尝试使用 hstack 并连接为:
np.hstack((a,b))
c=np.concatenate(a,b,0)
我被错误困住了
ValueError: all the input arrays must have same number of dimensions
请指导我连接和生成尺寸为 1460 x 11 的数组 c。
np.c_[a, b]
沿最后一个轴连接。
每 the docs、
... arrays will be stacked along their last axis after being upgraded to at least 2-D with 1's post-pended to the shape
由于 b
的形状为 (1460,)
,其形状在沿最后一个轴连接之前升级为 (1460, 1)
。
In [26]: c = np.c_[a,b]
In [27]: c.shape
Out[27]: (1460, 11)
尝试
b = np.expand_dims( b,axis=1 )
然后
np.hstack((a,b))
或
np.concatenate( (a,b) , axis=1)
将正常工作。
最基本的操作是:
np.concatenate((a,b[:,None]),axis=1)
[:,None]
位将 b
转换为 (1060,1)
数组。现在两个数组的第一个维度匹配,你可以很容易地连接第二个。
b
中添加第 2 维的方法有很多种,例如 reshape
和 expanddims
。 hstack
使用 atleast_1d
在这种情况下没有帮助。 atleast_2d
在错误的一侧添加了 None
。我强烈提倡学习 [:,None]
语法。
一旦数组都是二维的并且在正确的维度上匹配,连接就很容易了。