sluque
sluque

Reputation: 517

Assignment to numpy structured array

How does one assign to numpy structured arrays?

import numpy as np

baz_dtype = np.dtype([("baz1", "str"),
                      ("baz2", "uint16"),
                      ("baz3", np.float32)])
dtype = np.dtype([("foo", "str"),
                  ("bar", "uint16"),
                  ("baz", baz_dtype)])
xx = np.zeros(2, dtype=dtype)
xx["foo"][0] = "A"

Here xx remains unchanged. The docs https://docs.scipy.org/doc/numpy/user/basics.rec.html are a little vague on this.

On a related note, is it possible to make one or more of the subtypes be lists or numpy arrays of the specified dtype?

Any tips welcome.

Upvotes: 0

Views: 269

Answers (1)

user2357112
user2357112

Reputation: 280251

You're performing the assignment correctly. The part you've screwed up is the dtypes. NumPy string dtypes are fixed-size, and if you try to use "str" as a dtype, it's treated as size 0 - the empty string is the only possible value! Your "A" gets truncated to 0 characters to fit.

Specify a size - for example, 'S10' is 10-byte bytestrings, or 'U10' is 10-code-point unicode strings - or use object to store ordinary Python string objects and avoid the length restrictions and treatment of '\0' as a null terminator.

Upvotes: 3

Related Questions