python-3.x - 将列表数组转换为 numpy-nd 数组的问题
问题描述
我有一个列表数组
输入:
array([list([1, 1, 1]),
list([1, 1, 1])],dtype=object)
我想将其转换为 numpy nd-array:
输出:
array([[1., 1., 1.,],
[1., 1., 1.,]])
我试过这段代码:
import numpy as np
npa = np.asarray(someListOfLists, dtype=np.float32)
但是如果失败了。
解决方案
构建你的数组 - 简单的复制粘贴不会这样做:
In [467]: a = np.array([None,None])
In [468]: a[:] = [1,2,3],[4,5,6]
In [469]: a
Out[469]: array([list([1, 2, 3]), list([4, 5, 6])], dtype=object)
您的失败尝试,带有完整的回溯:
In [471]: np.asarray(a, dtype=np.float32)
TypeError: float() argument must be a string or a number, not 'list'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<ipython-input-471-a8170ed9d2a8>", line 1, in <module>
np.asarray(a, dtype=np.float32)
ValueError: setting an array element with a sequence.
它仍在尝试将 2 元素对象数组转换为 2 元素浮点数。
一种工作方式:
In [472]: np.stack(a)
Out[472]:
array([[1, 2, 3],
[4, 5, 6]])
其他
In [473]: a.tolist()
Out[473]: [[1, 2, 3], [4, 5, 6]]
In [474]: np.array(a.tolist())
Out[474]:
array([[1, 2, 3],
[4, 5, 6]])
推荐阅读
- php - Docker 调用未定义的函数 imagecreatefromjpeg()
- sql - SQL在特定的sql中获取多行
- git - 如何从 git 中的旧提交修复我的主分支
- r - 使用 ggplot 的一个变量直方图
- javascript - 使用不和谐机器人(Javascript)检查时间
- python - TensorFlow:数字/浮点数的激活函数是什么?
- trinitycore - 如何让 AzerothCore 和 TrinityCore 领域共享同一个 authserver
- javascript - 如何在数组中转换 Ajax 响应对象
- javascript - 如何创建表单添加按钮
- java - Java swing indeterminate JProgressBar 在到达终点而不是弹跳时从左侧开始