[英]convert Python scalar and numpy array of size 1 to scalar
I have a Python function that receives Python scalars or NumPy arrays of size 1. I would like to get the exact scalar out of this without too much complication. I have a Python function that receives Python scalars or NumPy arrays of size 1. I would like to get the exact scalar out of this without too much complication. item()
unconditionally converts to native Python types, so that's not good: item()
无条件地转换为本机 Python 类型,所以这不好:
a = np.array([1])
b = np.asarray(a).item()
print(a[0], type(a[0]))
print(b, type(b))
1 <class 'numpy.int64'>
1 <class 'int'>
I also need to scratch the asarray
since it converts to numpy types right away:我还需要asarray
,因为它会立即转换为 numpy 类型:
a = 1
b = np.asarray(a).flat[0]
print(a, type(a))
print(b, type(b))
1 <class 'int'>
1 <class 'numpy.int64'>
Any helper functions that I'm missing?我缺少任何辅助功能吗?
Based on your comment, I think you want (although this is not entirely clear from your post) to get the first item out of an array with length 1, but it should also work if the input is already an integer/float/complex number.根据您的评论,我认为您希望(尽管这在您的帖子中并不完全清楚)从长度为 1 的数组中获取第一项,但如果输入已经是整数/浮点数/复数,它也应该工作.
You can use type checking here:您可以在此处使用类型检查:
def GetItem(inputobject):
if type(inputobject) is np.ndarray:
return inputobject[0]
else:
return inputobject
example:例子:
>>> GetItem(np.array([2], dtype = np.complex128))
(2+0j)
>>> type(GetItem(np.array([2], dtype = np.complex128)))
np.complex128
>>> GetItem(42)
42
This won't work for many cases, like when the array is of shape
(1,1,1,1)
这在许多情况下都不起作用,例如当数组的形状为(1,1,1,1)
If your objects can have between 0 and some_large_number amount of dimensions but there is still only one item, this works:如果您的对象可以具有 0 到 some_large_number 数量的维度,但仍然只有一项,则此方法有效:
def GetItem(inputobject):
while type(inputobject) is np.ndarray:
inputobject = inputobject[0]
return inputobject
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.