3

Description

I have spent about an hour trying to hunt down a numpy array construction error. I must not be using numpy dtypes correctly but the error message is not descriptive enough and I am not given a good enough stack trace to find the error.

Simplified Example that creates same error:

 import numpy as np
 names = ['id', 'x']
 formats = [np.int64, np.float64]
 np.array([1, 1.0], dtype={'names': names, 'formats': formats})

The following code results in the error

 ----> 1 np.array([1, 1.0], dtype={'names': names, 'formats': formats})
 TypeError: a bytes-like object is required, not 'int'

So i get that the error occurs from the first element being an int but why is it expecting a bytes like object?

Answer: it has nothing to do with the fact that the first element is in int. The list needs to be a tuple see below.

2
  • uh, what exactly are you trying to do here? Commented Mar 16, 2017 at 21:11
  • Trying to construct a record array figured out the solution and it is not at all obvious. Numpy need to fix this. Commented Mar 16, 2017 at 21:16

1 Answer 1

6

The solution is that numpy requires a single tuple or list of tuples. Not a list of lists or list.

The following works

 np.array((1, 1.0), dtype={'names': names, 'formats': formats})

I find it frustrating that numpy gives no indication in the error that this is what is expected.

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

1 Comment

That requirement isn't as explicit on this docs page as it could be: docs.scipy.org/doc/numpy/user/basics.rec.html. There is also an example without commentary in docs for np.array: x = np.array([(1,2),(3,4)],dtype=[('a','<i4'),('b','<i4')])

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.