Python:如何在PyTables中存储一个numpy多维数组?

scr*_*pts 18 python arrays numpy multidimensional-array pytables

如何使用PyTables将numpy多维数组放入HDF5文件中?

据我所知,我不能在pytables表中放置一个数组字段.

我还需要存储有关此数组的一些信息,并能够对其进行数学计算.

有什么建议?

Joe*_*ton 33

可能有一种更简单的方法,但据我所知,这就是你要做的事情:

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()
Run Code Online (Sandbox Code Playgroud)

如果要指定要使用的压缩,请查看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()
Run Code Online (Sandbox Code Playgroud)

对于很多这个问题,可能有一种更简单的方法...... pytables在很长一段时间里,我还没有使用除了类似数据的数据.

注意:使用pytables 3.0,f.createCArray重命名为f.create_carray.它也可以直接接受数组,而不指定atom,

f.create_carray('/', 'somename', obj=x, filters=filters)
Run Code Online (Sandbox Code Playgroud)

  • 请注意,现在可以使用文件对象上的create_array方法更直接地完成此操作,如http://pytables.github.io/usersguide/tutorials.html上的"创建新数组对象"一节中所述. (6认同)