将列表列表放入 numpy 数组 [英] List of lists into numpy array

查看:61
本文介绍了将列表列表放入 numpy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I convert a simple list of lists into a numpy array? The rows are individual sublists and each row contains the elements in the sublist.

推荐答案

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

If your list of lists contains lists with varying number of elements then the answer of Ignacio Vazquez-Abrams will not work. Instead there are at least 3 options:

1) 创建一个数组数组:

1) Make an array of arrays:

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) 制作一个列表数组:

2) Make an array of lists:

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

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

3) First make the lists equal in length:

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)

这篇关于将列表列表放入 numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆