Can I Construct A Numpy Object Zero-d Array From Its Value In A Single Expression?
Solution 1:
I've answered this kind of question of a number of times, when people want to make a object array containing lists or tuples. All that's different here is you want to do this with a 0d array.
For example: Reduce Dimensons when converting list to array
This question contrasts:
np.array([[1,2],[3,4]]) # (2,2) int
np.array([[1],[3,4]]) # (2,) object
Making a (2,) object from the first list requires the create and fill approach. np.array(...)
insists on drilling down into a nested iterable as far as it can go. It's trained, so to speak, to create as high a dimensional array as it can. It will iterate on lists and tuples, but not on dictionaries or sets.
np.array
takes a ndmin
parameter, but not a ndmax
one. I believe there is some github issue about array creator that would limit that depth.
For now, creating a 'empty' object array of the right dimension, and filling it is best. And it's easy to get errors when filling, such as broadcasting or setting with sequences ones.
There's nothing wrong with your make_scalar
function. This isn't the kind of operation where speed matters. So your own function is just as pretty as a builtin one.
Another thought - scipy.io.loadmat
returns a lot of single element object arrays. It does this to represent MATLAB structures and cells. We could look at its code to see if that developer uses anything clever.
Relevant github issues:
https://github.com/numpy/numpy/issues/5933 Enh: Object array creation function
https://github.com/numpy/numpy/issues/6070 Please Deprecate creation of numpy arrays for arbitrary objects
Post a Comment for "Can I Construct A Numpy Object Zero-d Array From Its Value In A Single Expression?"