Numpy将2D数组与1D数组连接起来

2024-10-05 13:23:30 发布

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

我正在尝试连接4个数组,一个一维形状数组(78427,)和3个二维形状数组(78427375/81/103)。基本上这是4个具有78427个图像特征的数组,其中1D数组对每个图像只有1个值。

我尝试按如下方式连接数组:

>>> print X_Cscores.shape
(78427, 375)
>>> print X_Mscores.shape
(78427, 81)
>>> print X_Tscores.shape
(78427, 103)
>>> print X_Yscores.shape
(78427,)
>>> np.concatenate((X_Cscores, X_Mscores, X_Tscores, X_Yscores), axis=1)

这将导致以下错误:

Traceback (most recent call last): File "", line 1, in ValueError: all the input arrays must have same number of dimensions

问题似乎是一维数组,但我真的看不出原因(它也有78427个值)。在连接1D数组之前,我试图对其进行转置,但这也不起作用。

如果您对连接这些数组的正确方法有任何帮助,我们将不胜感激!


Tags: 图像np方式特征数组形状printshape
3条回答

你可以试试这句话:

concat = numpy.hstack([a.reshape(dim,-1) for a in [Cscores, Mscores, Tscores, Yscores]])

这里的“秘密”是在一个轴上使用已知的公共尺寸进行整形,在另一个轴上使用-1进行整形,并且它会自动匹配大小(如果需要,创建一个新的轴)。

我不确定你是否想要这样的东西:

a = np.array( [ [1,2],[3,4] ] )
b = np.array( [ 5,6 ] )

c = a.ravel()
con = np.concatenate( (c,b ) )

array([1, 2, 3, 4, 5, 6])

或者

np.column_stack( (a,b) )

array([[1, 2, 5],
       [3, 4, 6]])

np.row_stack( (a,b) )

array([[1, 2],
       [3, 4],
       [5, 6]])

尝试连接X_Yscores[:, None](或A[:, np.newaxis],如imaluengo所建议)。这将从一维数组中创建二维数组。

示例:

A = np.array([1, 2, 3])
print A.shape
print A[:, None].shape

输出:

(3,)
(3,1)

相关问题 更多 >

    热门问题