1

I'm trying to build a structured numpy array with a field that is a named bytes field (type 4b, not unicode).

import numpy as np 
dtype = np.dtype([('count', 'u8'), ('name', '4b')], align=True)
a = np.asarray([(10, b'test')], dtype=dtype)
print(a.dtype)

I receive the error:

ValueError: invalid literal for int() with base 10: b'test'

Now, if i change the bytes field to unicode,

import numpy as np 
dtype = np.dtype([('count', 'u8'), ('name', 'U4')], align=True)
a = np.asarray([(10, 'test')], dtype=dtype)
print(a.dtype)

this does not result in an error and I get the output:

{'names':['count','name'], 'formats':['<u8','<U4'], 'offsets':[0,8], 'itemsize':24, 'aligned':True}

But to me this is a hack since I specifically just want bytes.

Question: How can I get a named bytes field on my structured numpy array?

1 Answer 1

2

You can use the S type string to work with byte strings:

>>> dtype = np.dtype([('count', 'u8'), ('name', 'S4')], align=True)
>>> a = np.array([(10, b'test')], dtype=dtype)
>>> a
array([(10, b'test')],
      dtype={'names':['count','name'], 'formats':['<u8','S4'], 'offsets':[0,8], 'itemsize':16, 'aligned':True})
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.