python - 列表列表到 numpy 数组中

如何将简单的列表列表转换为 numpy 数组?这些行是单独的子列表,每一行都包含子列表中的元素。

最佳答案

如果您的列表列表包含具有不同数量元素的列表,那么 Ignacio Vazquez-Abrams 的答案将不起作用。相反,至少有 3 个选项:

1) 制作数组数组:

x=[[1,2],[1,2,3],[1]]
y=numpy.array([numpy.array(xi) for xi in x])
type(y)
>>><type 'numpy.ndarray'>
type(y[0])
>>><type 'numpy.ndarray'>

2) 制作一个列表数组:

x=[[1,2],[1,2,3],[1]]
y=numpy.array(x)
type(y)
>>><type 'numpy.ndarray'>
type(y[0])
>>><type 'list'>

3) 首先使列表长度相等:

x=[[1,2],[1,2,3],[1]]
length = max(map(len, x))
y=numpy.array([xi+[None]*(length-len(xi)) for xi in x])
y
>>>array([[1, 2, None],
>>>       [1, 2, 3],
>>>       [1, None, None]], dtype=object)

https://stackoverflow.com/questions/10346336/

相关文章:

linux - 如何让 sed 从标准输入中读取?

linux - 在 Bash 脚本中引发错误

linux - 如何 cat <> 包含代码的文件?

python - 如何通过 Django 发送电子邮件?

python - 什么是好的速率限制算法?

linux - bash - 如何将结果从 which 命令传送到 cd

python - Python中有标签/转到吗?

python - os.path.dirname(__file__) 返回空

python - 如何在 Python 中获取线程 id?

c - dup2/dup - 为什么我需要复制文件描述符?