你考虑过 Numpy 数组吗?
当您的数据太大而无法放入内存时,PyTables 非常棒,但是 8 字节浮点数的 200x2000 矩阵只需要大约 3MB 的内存。所以我认为 PyTables 可能有点矫枉过正。
np.savetxt
您可以使用or (用于压缩)将 numpy 数组保存到文件中,并且可以使用ornp.savez
从文件中读取它们。np.loadtxt
np.load
如果您有许多这样的数组要存储在磁盘上,那么我建议使用数据库而不是 numpy.npz
文件。顺便说一句,要在数据库中存储一个 200x2000 的矩阵,您只需要 3 个表列:行、列、值:
import sqlite3
import numpy as np
db = sqlite3.connect(':memory:')
cursor = db.cursor()
cursor.execute('''CREATE TABLE foo
(row INTEGER,
col INTEGER,
value FLOAT,
PRIMARY KEY (row,col))''')
ROWS=4
COLUMNS=6
matrix = np.random.random((ROWS,COLUMNS))
print(matrix)
# [[ 0.87050721 0.22395398 0.19473001 0.14597821 0.02363803 0.20299432]
# [ 0.11744885 0.61332597 0.19860043 0.91995295 0.84857095 0.53863863]
# [ 0.80123759 0.52689885 0.05861043 0.71784406 0.20222138 0.63094807]
# [ 0.01309897 0.45391578 0.04950273 0.93040381 0.41150517 0.66263562]]
# Store matrix in table foo
cursor.executemany('INSERT INTO foo(row, col, value) VALUES (?,?,?) ',
((r,c,value) for r,row in enumerate(matrix)
for c,value in enumerate(row)))
# Retrieve matrix from table foo
cursor.execute('SELECT value FROM foo ORDER BY row,col')
data=zip(*cursor.fetchall())[0]
matrix2 = np.fromiter(data,dtype=np.float).reshape((ROWS,COLUMNS))
print(matrix2)
# [[ 0.87050721 0.22395398 0.19473001 0.14597821 0.02363803 0.20299432]
# [ 0.11744885 0.61332597 0.19860043 0.91995295 0.84857095 0.53863863]
# [ 0.80123759 0.52689885 0.05861043 0.71784406 0.20222138 0.63094807]
# [ 0.01309897 0.45391578 0.04950273 0.93040381 0.41150517 0.66263562]]
如果你有很多这样的 200x2000 矩阵,你只需要一个表格列来指定哪个矩阵。