1

I want to match the output of some existing code that I do not have access to. The existing code produces a structure of nested numpy arrays and lists.

Desired output:

array([array([[0]], dtype = uint8)], dtype = object)

Actual input:

np.array([np.array([[0]], dtype = 'uint8')], dtype = object)

Actual output:

array([[[0]]], dtype = object)

It seems that the outer numpy array is overriding the dtype of the inner numpy array. Any thoughts of how to achieve my desired output?

1 Answer 1

3

The most robust way of making an object dtype array of a given shape, is to initial one, and assign values:

In [107]: res = np.empty(1, object)
In [108]: res
Out[108]: array([None], dtype=object)
In [109]: res[0] = np.array([[0]], 'uint8')
In [110]: res
Out[110]: array([array([[0]], dtype=uint8)], dtype=object)

np.array is a complicated function. Its first, apparent, priority is to make a multidimensional array with the given dtype. It will change the dtype of the inputs as needed. What you seek is something it does as a fallback strategy.

In [112]: np.array([np.array([[0]]), None], object)
Out[112]: array([array([[0]]), None], dtype=object)
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.