0

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.

1

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.