2012-01-12 113 views
16

如何使用PyTables将一个numpy多维数组放入HDF5文件中?Python:如何在PyTables中存储一个numpy多维数组?

从我能告诉我不能把数组字段放在pytables表中。

我还需要存储一些关于这个数组的信息,并且能够对它进行数学计算。

有什么建议吗?

+8

老实说,如果你存储大量的只是直线上升ND数组,你用'h5py',而不是'pytables'更好。它和'f.create_dataset('name',data = x)'一样简单''其中'x'是你的numpy数组,'f'是开放的hdf文件。在'pytables'中做同样的事情是可能的,但是相当困难。 – 2012-01-12 22:16:55

+0

Joe,+1。我即将发表几乎相同的评论。 – 2012-01-12 22:21:07

+0

我想到了,但pytables有一些功能(tables.expr)直接在数组上进行计算,我可以用h5py做到吗? – scripts 2012-01-12 22:22:25

回答

32

有可能是一个更简单的方法,但这是你如何去这样做,因为据我所知:

import numpy as np 
import tables 

# Generate some data 
x = np.random.random((100,100,100)) 

# Store "x" in a chunked array... 
f = tables.openFile('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.openFile('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。它也可以直接接受阵列,而不指定​​,

f.create_carray('/', 'somename', obj=x, filters=filters) 
+0

谢谢它的工作完美无瑕! – scripts 2012-01-12 23:32:43

+5

请注意,现在可以使用文件对象上的create_array方法更直接地完成此操作,如http://pytables.github.io/usersguide/tutorials.html中的'创建新的数组对象'部分所述。 – 2014-10-02 15:52:52

相关问题