【问题标题】:Python: how to store a numpy multidimensional array in PyTables?Python:如何在 PyTables 中存储一个 numpy 多维数组?
【发布时间】:2012-02-09 05:07:04
【问题描述】:

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

据我所知,我不能将数组字段放入 pytables 表中。

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

有什么建议吗?

【问题讨论】:

  • 老实说,如果您要存储大量直接向上的 ND 阵列,最好使用 h5py 而不是 pytables。它就像f.create_dataset('name', data=x) 一样简单,其中x 是您的numpy 数组,f 是打开的hdf 文件。在pytables 中做同样的事情是可能的,但要困难得多。
  • 乔,+1。我正要发表几乎相同的评论。
  • 我想到了,但是 pytables 有一些特性(tables.expr)可以直接在数组上进行计算,我可以用 h5py 来做吗?
  • @scripts - 不像pytables 那样采用压缩、加速的方式。 (或者至少我不知道,无论如何。)pytables 也会给你很多很好的查询能力。 h5py 更适合于磁盘阵列的直接存储和切片(并且更 Pythonic,i.m.o.)。不要过多地插入我自己的答案,但我对两者之间权衡的想法在这里:stackoverflow.com/questions/7883646/…
  • 感谢 Joe Kington 提供的信息,因为强大的查询技术,pytables 更适合我的情况

标签: python arrays multidimensional-array numpy pytables


【解决方案1】:

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

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)

【讨论】:

  • 请注意,现在可以在文件对象上使用 create_array 方法更直接地完成此操作,如 pytables.github.io/usersguide/tutorials.html 的“创建新数组对象”部分所述
  • AttributeError: 'File' object has no attribute 'createCArray'
猜你喜欢
  • 2012-05-25
  • 2016-02-13
  • 1970-01-01
  • 2021-11-29
  • 2012-03-03
  • 2015-03-14
  • 1970-01-01
  • 1970-01-01
  • 2021-05-01
相关资源
最近更新 更多