[Numpy-discussion] structured array with submember assign
Derek Homeier
derek at astro.physik.uni-goettingen.de
Mon Dec 26 16:28:07 EST 2011
On 26.12.2011, at 7:37PM, Fabian Dill wrote:
> I have a problem with a structured numpy array.
> I create is like this:
> tiles = numpy.zeros((header["width"], header["height"],3), dtype = numpy.uint8)
> and later on, assignments such as this:
> tiles[x, y,0] = 3
>
> Now uint8 is not sufficient anymore, but only for the first of the 3 values.
> uint16 for all of them would use too much ram (increase of 1-3 GB)
>
> I have tried using structured arrays, but the dtype is essentially always a tuple.
>
> tiles = numpy.zeros((header["width"], header["height"], 1), dtype = "u2,u1,u1")
>
> tiles[x, y,0] = 0
> TypeError: expected an object with a buffer interface
>
If you create a structured array, you probably don't want the third dimension, as the
structure already spans three fields, and to assign to it you either need to address
the fields explicitly (with the default field names 'f0', 'f1', 'f2'), or use an array with
corresponding dtype:
>>> dt = "u2,u1,u1"
>>> tiles = numpy.zeros((2,3), dtype=dt)
>>> tiles
array([[(0, 0, 0), (0, 0, 0), (0, 0, 0)],
[(0, 0, 0), (0, 0, 0), (0, 0, 0)]],
dtype=[('f0', '<u2'), ('f1', '|u1'), ('f2', '|u1')])
>>> tiles['f0'][0] = 1
>>> tiles[0,1] = np.array((3,4,5), dtype=dt)
>>> tiles
array([[(1, 0, 0), (3, 4, 5), (1, 0, 0)],
[(0, 0, 0), (0, 0, 0), (0, 0, 0)]],
dtype=[('f0', '<u2'), ('f1', '|u1'), ('f2', '|u1')])
Cheers,
Derek
More information about the NumPy-Discussion
mailing list