我正在尝试将一些MATLAB代码转换为Python。MATLAB的数据集数组在Python中有没有等效的结构?http://www.mathworks.com/help/stats/dataset-arrays.html
回答:
如果你想对数据集进行数值运算,numpy
将是你的选择。你可以通过组合基本的numpy dtypes
来指定任意记录类型,并通过字段名访问记录,类似于Python内置的字典访问方式。
import numpymyDtype = numpy.dtype([('name', numpy.str_), ('age', numpy.int32), ('score', numpy.float64)])myData = numpy.empty(10, dtype=myDtype) # 创建空数据集print myData['age'] # 打印所有年龄
你甚至可以使用numpy中的tofile
和fromfile
函数保存和重新加载这些数据,并继续使用命名字段:
with open('myfile.txt', 'wb') as f: numpy.ndarray.tofile(myData, f)with open('myfile.txt', 'rb') as f: loadedData = numpy.fromfile(f, dtype=myDtype) print loadedData['age']