首页 文章

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

提问于
浏览
13

我试图连接4个数组,一个1D数组形状(78427,)和3个2D数组形状(78427,375 / 81/103) . 基本上这是具有78427个图像的特征的4个阵列,其中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(最近一次调用最后一次):ValueError中的文件“”,第1行:所有输入数组必须具有相同的维数

问题似乎是一维数组,但我不能真正理解为什么(它还有78427个值) . 我尝试在连接之前转置1D阵列,但这也没有用 .

任何有关连接这些数组的正确方法的帮助将不胜感激!

3 回答

  • 12

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

    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]])
    
  • 4

    尝试连接 X_Yscores[:, None] (或imaluengo建议的 A[:, np.newaxis] ) . 这将创建一维数组中的2D数组 .

    例:

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

    输出:

    (3,)
    (3,1)
    
  • 3

    你可以试试这个单行:

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

    这里的“秘密”是使用一个轴上的已知公共维度重新整形,另一个轴使用-1,并自动匹配大小(如果需要,创建一个新轴) .

相关问题