如何创建一个PyTables表来存储一个巨大的方阵?

问题描述

我正在尝试创建一个PyTables表以在其中存储200000 * 200000矩阵。 我尝试以下代码

import tables
columns = {}
for x in range (200000):
    columns['col' + str(x)] = tables.FloatCol()
h5f = tables.open_file('matrix1.h5','w')
tbl = h5f.create_table('/','matrix',columns)
h5f.close()

,但此回溯失败:

  File "/home/nick/tests0/reg/create_tables.py",line 18,in <module>
    tbl = h5f.create_table('/',columns)

  File "/home/nick/anaconda3/lib/python3.8/site-packages/tables/file.py",line 1053,in create_table
    ptobj = Table(parentnode,name,File "/home/nick/anaconda3/lib/python3.8/site-packages/tables/table.py",line 835,in __init__
    super(Table,self).__init__(parentnode,new,filters,File "/home/nick/anaconda3/lib/python3.8/site-packages/tables/leaf.py",line 286,in __init__
    super(Leaf,_log)

  File "/home/nick/anaconda3/lib/python3.8/site-packages/tables/node.py",line 264,in __init__
    self._v_objectid = self._g_create()

  File "/home/nick/anaconda3/lib/python3.8/site-packages/tables/table.py",line 1022,in _g_create
    self._v_objectid = self._create_table(

  File "tables/tableextension.pyx",line 211,in tables.tableextension.Table._create_table

HDF5ExtError: Problems creating the table

我在做什么错了?

解决方法

那是一个很大的矩阵(如果全部为整数,则为300GB)。可能您将不得不增量编写。 (我的系统没有足够的RAM来一次完成所有操作。)

不查看数据类型,很难给出具体建议。
第一个问题:您真的要创建一个还是一个 Array 就足够了? PyTables有两种类型。有什么区别?
Array 保存同类数据(如NumPy ndarray),并且可以具有任意维。 通常用于保存异构数据(如NumPy数组),并且始终为2d(实际上是1d 结构化类型的数组)。表格还通过PyTables API支持复杂的查询。

创建的关键是使用description=obj=参数来描述每一行的结构化类型(和字段名称)。我最近发布了一个答案,该答案显示了如何创建表。请查阅。您可能会发现不想创建200000个字段/列来定义表。查看此答案:different data types for different columns of an array

如果只想保存200000x200000齐次实体的矩阵,则数组会更容易。 (鉴于数据大小,您可能需要使用EArray,以便可以递增地写入数据。)我编写了一个简单的示例,该示例创建了一个具有2000x200000实体的EArray,然后添加了3组数据(每组2000行;总计) 8000行)。

  • shape=(0,nrows)参数指示第一个轴可以是 扩展,并创建ncols列。
  • expectedrows=nrows参数在大型数据集中对于 I / O性能不佳。

生成的HDF5文件为6GB。重复earr.append(arr) 99次以获取200000行。下面的代码:

import tables as tb
import numpy as np

nrows=200000
ncols=200000
arr = np.arange(2000*ncols).reshape(2000,ncols)
h5f = tb.File('matrix1.h5','w')
earr = h5f.create_earray('/','myarray',shape=(0,ncols),expectedrows=nrows,obj=arr)
earr.append(arr)
earr.append(arr)
earr.append(arr)

h5f.close()