我可以在单个表达式中根据其值构造一个numpy对象的零维数组吗? [英] Can I construct a numpy object zero-d array from its value in a single expression?
问题描述
所有这些工作(即具有.shape == ()
):
These all work (ie, have .shape == ()
):
np.array(1, dtype=object)
np.array("foo", dtype=object)
np.array(object(), dtype=object)
但这不是:
np.array((0, 0), dtype=object) # .shape == (2,)
我可以通过以下两个任务来实现这一目标:
I can achieve this with two assignments as:
def make_scalar(x):
value = np.empty((), dtype=object)
value[()] = x
return value
make_scalar((0, 0)) # .shape == ()
是否有内置函数可以让我在单个表达式中创建此0d数组(用于任意标量值)?
Is there a builtin function that will allow me to create this 0d array in a single expression (for arbitrary scalar values)?
推荐答案
当人们想要创建一个包含列表或元组的对象数组时,我已经回答了很多此类问题.唯一不同的是,您要使用0d数组进行此操作.
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.
这个问题与之相反:
np.array([[1,2],[3,4]]) # (2,2) int
np.array([[1],[3,4]]) # (2,) object
从第一个列表中创建(2,)对象需要使用create and fill方法. np.array(...)
坚持尽可能深入到嵌套的可迭代对象中.可以说,它经过训练可以创建尽可能高的维数组.它将在列表和元组上迭代,但不会在字典或集合上进行迭代.
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
带有一个ndmin
参数,但没有一个ndmax
参数.我相信关于数组创建器的github问题会限制该深度.
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.
make_scalar
函数没有任何问题.这不是速度重要的操作.因此,您自己的功能就像内置功能一样.
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.
另一个想法-scipy.io.loadmat
返回很多单元素对象数组.这样做是为了表示MATLAB结构和单元.我们可以看一下它的代码,看看该开发人员是否使用了任何聪明的方法.
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.
相关的github问题:
Relevant github issues:
https://github.com/numpy/numpy/issues/5933 恩:对象数组创建功能
https://github.com/numpy/numpy/issues/5933 Enh: Object array creation function
https://github.com/numpy/numpy/issues/6070 请反对为任意对象创建numpy数组
https://github.com/numpy/numpy/issues/6070 Please Deprecate creation of numpy arrays for arbitrary objects
这篇关于我可以在单个表达式中根据其值构造一个numpy对象的零维数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!