Python:如何在PyTables中存储numpy多维数组?
我该如何使用PyTables把一个numpy的多维数组放进HDF5文件里呢?
根据我的了解,我不能把数组字段放进pytables的表格里。
我还需要存储一些关于这个数组的信息,并且能够对它进行数学运算。
有什么建议吗?
1 个回答
34
可能有更简单的方法,但根据我所知道的,这就是你可以这样做的步骤:
import numpy as np
import tables
# Generate some data
x = np.random.random((100,100,100))
# Store "x" in a chunked array...
f = tables.open_file('test.hdf', 'w')
atom = tables.Atom.from_dtype(x.dtype)
ds = f.createCArray(f.root, 'somename', atom, x.shape)
ds[:] = x
f.close()
如果你想指定使用的压缩方式,可以看看 tables.Filters
。比如说:
import numpy as np
import tables
# Generate some data
x = np.random.random((100,100,100))
# Store "x" in a chunked array with level 5 BLOSC compression...
f = tables.open_file('test.hdf', 'w')
atom = tables.Atom.from_dtype(x.dtype)
filters = tables.Filters(complib='blosc', complevel=5)
ds = f.createCArray(f.root, 'somename', atom, x.shape, filters=filters)
ds[:] = x
f.close()
其实很多时候可能有更简单的方法……我很久没用过 pytables
处理其他类型的数据了,基本上只用它来处理表格数据。
注意:在 pytables 3.0 版本中,f.createCArray
被改名为 f.create_carray
。现在你也可以直接传入数组,而不需要指定 atom
,
f.create_carray('/', 'somename', obj=x, filters=filters)