如何使用`slice`对象读取pytables.CArray?

1 投票
1 回答
571 浏览
提问于 2025-04-17 13:21

我该如何使用 slice 对象来访问 tables.CArray?我现在有的代码是

In:  coord_slice
Out: [slice(0, 31, None), slice(0, 5760, None), slice(0, 2880, None)]

In:  _ds
Out:  /data/mydata (CArray(31, 5760, 2880), shuffle, blosc(5)) ''
      atom := Float32Atom(shape=(), dflt=0.0)
      maindim := 0
      flavor  := 'numpy'
      byteorder := 'little'
      chunkshape := (1, 45, 2880)

In: _ds[coord_slice]
Out: *** TypeError: long() argument must be a string or a number, not 'slice'

1 个回答

1

接下来是一个来自tables.CArray文档的修改示例。如果coord_slice是一个tuple(元组),而不是list(列表),那么你的代码应该可以正常运行。这里有一个在Github上关闭的问题,里面有一些线索,解释了为什么列表和元组不能互换使用

import tables
import numpy

fileName = 'carray1.h5'
shape = (200, 300)
atom = tables.UInt8Atom()
filters = tables.Filters(complevel=5, complib='zlib')

h5f = tables.openFile(fileName, 'w')
ca = h5f.createCArray(h5f.root, 'carray', atom, shape, filters=filters)

coord_slice = [slice(10,60,None),slice(20,70,None)]

# attempt to do multi-dimensional indexing with coord_slice as a list
try:
    ca[coord_slice] = numpy.ones((50, 50))
except TypeError:
    print 'TypeError was thrown with list'

# convert coord_slice to a tuple and try again.  This should work.
coord_slice = tuple(coord_slice)
try:
    ca[coord_slice] = numpy.ones((50, 50))
except TypeError:
    print 'TypeError was thrown with tuple'


print ca[coord_slice]
h5f.close()

撰写回答