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


当前回答

OP指定“行是单独的子列表,每行包含子列表中的元素”。

假设numpy的使用不被禁止(假设numpy已经被添加到OP中),使用vstack:

import numpy as np

list_of_lists= [[1, 2, 3], [4, 5, 6], [7 ,8, 9]]

array = np.vstack(list_of_lists)
# array([[1, 2, 3],
#        [4, 5, 6],
#        [7, 8, 9]])

或者更简单一点(在另一个答案中提到),

array = np.array(list_of_lists)

其他回答

>>> numpy.array([[1, 2], [3, 4]]) 
array([[1, 2], [3, 4]])

OP指定“行是单独的子列表,每行包含子列表中的元素”。

假设numpy的使用不被禁止(假设numpy已经被添加到OP中),使用vstack:

import numpy as np

list_of_lists= [[1, 2, 3], [4, 5, 6], [7 ,8, 9]]

array = np.vstack(list_of_lists)
# array([[1, 2, 3],
#        [4, 5, 6],
#        [7, 8, 9]])

或者更简单一点(在另一个答案中提到),

array = np.array(list_of_lists)

其实很简单:

>>> lists = [[1, 2], [3, 4]]
>>> np.array(lists)
array([[1, 2],
       [3, 4]])

就用熊猫吧

list(pd.DataFrame(listofstuff).melt().values)

这只适用于列表的列表

如果你有一个列表的列表的列表,你可能想尝试一些沿着

lists(pd.DataFrame(listofstuff).melt().apply(pd.Series).melt().values)

如果列表的列表包含元素数量不同的列表,那么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)