使用pytables构建大型numpy数组

7 投票
2 回答
9414 浏览
提问于 2025-04-17 09:04

我想知道怎么用pytables创建一个很大的numpy数组。我试过这样做,但出现了“ValueError: array is too big.”的错误:

import numpy as np
import tables as tb
ndim = 60000
h5file = tb.openFile('test.h5', mode='w', title="Test Array")
root = h5file.root
h5file.createArray(root, "test", np.zeros((ndim,ndim), dtype=float))
h5file.close()

2 个回答

15

接着 @b1r3k 的回答,如果你想创建一个数组,但不打算一次性把所有数据都加载到内存中(也就是说,不想一次性把整个数组都放进电脑的记忆里),那么你可以使用 CArray(分块数组)。这个方法的意思是,你可以逐步地填充和访问这个数组的数据:

import numpy as np
import tables as tb
ndim = 60000
h5file = tb.openFile('test.h5', mode='w', title="Test Array")
root = h5file.root
x = h5file.createCArray(root,'x',tb.Float64Atom(),shape=(ndim,ndim))
x[:100,:100] = np.random.random(size=(100,100)) # Now put in some data
h5file.close()
8

你可以尝试使用 tables.CArray 类,因为它支持压缩,不过……

我觉得这个问题更像是关于 numpy 而不是 pytables,因为你是在用 numpy 创建数组,然后再用 pytables 存储它。

这样的话,你需要很多内存来执行 np.zeros((ndim,ndim),这可能就是出现“ValueError: array is too big.”这个错误的地方。

如果你的矩阵/数组不是很稠密的话,你可以使用 scipy 提供的稀疏矩阵表示:http://docs.scipy.org/doc/scipy/reference/sparse.html

另一个解决办法是,如果你不需要一次性加载整个数组,可以尝试分块访问你的数组——可以看看这个讨论:使用 Python 和 NumPy 处理非常大的矩阵

撰写回答