如何在Python中将嵌套数组转换为多维数组(张量)

时间:2019-11-23 22:01:27

标签: python arrays numpy

我正在处理嵌套数组,该数组看起来像:

feat=np.load('feat.npy',allow_pickle=True)
print(feat)
->array([array([[-1.0160675e+01, -1.3804866e+01,  9.1880971e-01, ...,
         1.5415058e+00,  1.1875046e-02, -5.8664594e+00],
       [-9.9697800e+00, -1.3823588e+01, -7.0778362e-02, ...,
         1.5948311e+00,  4.3481258e-01, -5.1646194e+00],
       [-9.9518738e+00, -1.2771760e+01, -1.2623003e-01, ...,
         3.4290311e+00,  2.7361808e+00, -6.0621500e+00],
       ...,
       [-9.9772453e+00, -1.8227636e+01,  5.4514462e-01, ...,
        -2.4311361e+01, -1.2033378e+01, -3.0492477e+00],
       [-9.8815651e+00, -1.3674727e+01,  5.1737971e+00, ...,
        -1.0951551e+01, -2.6184993e+00,  1.5815194e+00],
       [-1.0164914e+01, -1.2636200e+01,  4.4198503e+00, ...,
        -5.7269883e+00,  4.0758374e-01, -4.4462643e+00]], dtype=float32),
       array([[-12.862341 ,  -5.968506 , -20.532919 , ...,   3.1745207,
          6.5410886,  -8.223573 ],
       [-13.071164 ,  -6.0360484, -19.319475 , ...,   7.5193286,
          2.9258938, -13.224365 ],
       [-13.512331 ,  -4.9030676, -14.524248 , ...,  12.339673 ,
          4.6204743, -15.382669 ],
       ...,
       [-11.605266 ,  -7.1909204, -33.44656  , ..., -11.974911 ,
         12.825395 ,  10.635098 ],
       [-11.769397 ,  -9.340318 , -34.413307 , ..., -10.077869 ,
          8.821722 ,   7.704534 ],
       [-12.301968 , -10.67318  , -32.46104  , ...,  -6.829077 ,
         15.29837  ,  13.100596 ]], dtype=float32),

,我使用numpy.ndarray.shape来获得数组的形状是(105835,),而数组的第一个元素是(99,13),有什么方法可以将嵌套数组转换为多维数组,例如((105835,99,13)??

我尝试了np.stack但它报告:

all input arrays must have the same shape

如果我使用np.vstack,它将变成2D数组:

temp=np.vstack(x)
temp.shape
->(9215279, 13)

1 个答案:

答案 0 :(得分:0)

您是否可以通过任何方式发布整形数组的代码部分?我继续尝试以下对我来说很好的方法:

    import numpy
    #build random array
    array1 = [[[] for i in range(5)] for j in range(5)]
    numpy.shape(array1)

它为我输出(5,5,0)。

下面是我为回答您的评论所做的第一个编辑:

我仍然认为我需要查看您如何尝试在代码中调整数组的形状。这就是我所做的,并且没有错误:

    a = array([array([[1,2,3],[1,2,3]]),array([[1,2,3],[1,2,3]])])
    b = shape(a)
    print(b)

它会打印出(2,2,3)。