首页 > 解决方案 > 将包含嵌套数组(不等形状)的列表转换为数组

问题描述

我有一个包含嵌套数组的列表,其中包含以下内容:

X_train_list=[array([ 6, 8, 6, ..., 6, 10, 1]), 
              array([4, 4, 4, ..., 4, 4, 1]),
              array([[ 1.00000000e+00,  7.94511008e-02,  1.69902773e-01, ...,
                      -2.14712075e-03, -6.92096074e-01,  4.39955591e-01],
                       [ 0.00000000e+00, -2.67692290e+00,  3.91302228e+00, ...,
                        -2.14712075e-03,  7.48800957e-02, -1.24420247e+00],
                       [ 0.00000000e+00, -4.54040642e-01, -1.18029496e-01, ...,
                        -2.14712075e-03,  1.12293567e-01, -6.15915526e-01]])]

当我找到数组的形状时:

for i in range(0,len(X_train_list):
    print((X_train_list[i]).shape)

表明:

 (486952,)
 (486952,)
 (486952, 21)

我想将此列表转换为数组:

arr_X_train_list = np.asarray(X_train_list)

但我收到以下错误:

ValueError: could not broadcast input array from shape (486952,21) into shape (486952)

以及有关如何将列表转换为数组的建议?

标签: pythonpython-3.xnumpy

解决方案


我假设您希望以形状数组 (486952, 23) 结束。可以通过向 X_train_list 中的简单数组添加维度并连接第二个轴上的所有内容来完成:

resul = np.concatenate([i if len(i.shape) == 2 else i.reshape(len(i), 1)
                        for i in X_train_list], axis=1)

推荐阅读