首页 > 解决方案 > 将列表数组转换为 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)

但是如果失败了。

标签: python-3.xpandasnumpy

解决方案


构建你的数组 - 简单的复制粘贴不会这样做:

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

推荐阅读