andreas-h
andreas-h

Reputation: 11100

How to use `slice` objects to read a pytables.CArray?

How can I use slice objects to access a tables.CArray? What I currently have is

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'

Upvotes: 1

Views: 585

Answers (1)

John Vinyard
John Vinyard

Reputation: 13505

What follows is a modified example from the documentation for tables.CArray. If coord_slice is a tuple instead of a list, your code should work. Here's a closed issue on Github with some clues as to why lists and tuples can't be used interchangeably.

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()

Upvotes: 1

Related Questions