python - 将包含嵌套数组(不等形状)的列表转换为数组
问题描述
我有一个包含嵌套数组的列表,其中包含以下内容:
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)
以及有关如何将列表转换为数组的建议?
解决方案
我假设您希望以形状数组 (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)
推荐阅读
- javascript - React Native 和 Graphql 实时聊天应用程序无法在 iOS Expo Go 上运行
- mongodb - Mongo Atlas 搜索索引数字字段精确匹配搜索
- node.js - Supertest:在 Jest 环境被拆除后,您正在尝试“导入”一个文件
- katalon-studio - 从全局变量中检索值的计数并从值中选择任意随机数
- python - 如何更改列表列表中的值?
- linux - 关于linux socket buffer中read buffer和write buffer使用的内存问题
- java - 为什么函数组合在 IntFunction 中不可用
- python - python 虹膜检测决策树
- css - css 变量名可以以数字开头吗?
- tree - 使用 Protégé Project 可视化分类结构