列表列表成numpy数组 [英] List of lists into numpy array
本文介绍了列表列表成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屋!
查看全文