Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

python - Numpy array containing a numpy array of a different dtype

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?

question from:https://stackoverflow.com/questions/65927245/numpy-array-containing-a-numpy-array-of-a-different-dtype

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...