将嵌套的数据列表转换为多维Numpy数组 [英] Converting nested lists of data into multidimensional Numpy arrays

查看:2514
本文介绍了将嵌套的数据列表转换为多维Numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我正在嵌套列表中构建数据.在for循环之后,我想将其尽可能整洁地转换为多维Numpy数组.但是,当我对其执行数组转换时,似乎只将外部列表转换为数组.更糟糕的是,当我继续向下移动时,我将dataPoints的形状定为(100L,) ...因此是一个列表数组,其中每个列表都是我的数据(显然我想要一个(100,3)).我也尝试过使用numpy.asanyarray()进行欺骗,但似乎无法解决.如果可能的话,我真的希望从一开始就从我的3d列表中获得3d数组.如果没有,如何将列表数组转换为2d数组,而不必迭代并将其全部转换?

In the code below I am building data up in a nested list. After the for loop what I would like is to cast it into a multidimensional Numpy array as neatly as possible. However, when I do the array conversion on it, it only seems to convert the outer list into an array. Even worse when I continue downward I wind up with dataPoints as shape (100L,)...so an array of lists where each list is my data (obviously I wanted a (100,3)). I have tried fooling with numpy.asanyarray() also but I can't seem to work it out. I would really like a 3d array from my 3d list from the outset if that is possible. If not, how can I get the array of lists into a 2d array without having to iterate and convert them all?

我也愿意从一开始就采用更好的方法来结构化数据,如果这样可以简化处理的话.但是,它是通过串行端口传来的,大小事先未知.

I am also open to better way of structuring the data from the outset if it makes processing easier. However, it is coming over a serial port and the size is not known beforehand.

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

推荐答案

dataPoints不是二维列表.首先将其转换为2d列表,然后将起作用:

dataPoints is not a 2d list. Convert it first into a 2d list and then it will work:

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

现在d是您想要的(100,3).

Now d is (100,3) as you wanted.

这篇关于将嵌套的数据列表转换为多维Numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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