将嵌套的数据列表转换为多维Numpy数组

时间:2012-12-06 15:29:41

标签: python list numpy slice

在下面的代码中,我将在嵌套列表中构建数据。在for循环之后,我想要尽可能整齐地将它转换为多维Numpy数组。但是,当我对它进行数组转换时,它似乎只将外部列表转换为数组。更糟糕的是,当我继续向下时,我最终将dataPoints作为形状(100L,) ......所以列表数组中每个列表都是我的数据(显然我想要(100,3))。我曾试图欺骗numpy.asanyarray(),但我似乎无法解决这个问题。如果可能的话,我真的很喜欢我的3D列表中的3d数组。如果没有,我如何将列表数组放入二维数组而不必迭代并将它们全部转换?

编辑:如果它使处理更容易,我也会从一开始就更好地构建数据。但是,它是通过串行端口进行的,并且事先不知道大小。

import numpy as np
import time

data = []
for _i in range(100):   #build some list of lists
    d = [np.random.rand(), np.random.rand(), np.random.rand()]
    data.append([d,time.clock()])

dataArray = np.array(data)  #now I have an array of lists of a list(of data) and a time
dataPoints = dataArray[:,0] #this is the data in an array of lists

2 个答案:

答案 0 :(得分:5)

dataPoints不是2d列表。首先将它转换为2d列表,然后它将起作用:

d=np.array(dataPoints.tolist())

现在d是(100,3)你想要的。

答案 1 :(得分:-1)

如果你想要一个二维数组:

from itertools import chain
dataArray = np.array(list(chain(*data)),shape=(100,3))

我没有计算出代码,因此您可能需要更改列/行排序以使形状匹配。