[英]overloading a float to a numpy array
I have a function, processing a 1D numpy array, like this: 我有一个函数,处理一维numpy数组,如下所示:
def f(arr):
arr=asarray(arr)
#process data as numpy array
#...
return arr
With asarray
I allow to call the function with a list as f([4,5,6])
. 使用asarray
我允许使用列表调用函数f([4,5,6])
。 Now, I would like to "overload" the argument also to a single float, so that I can use f(4)
instead of f([4])
. 现在,我想将参数“重载”到一个浮点数,这样我就可以用f(4)
代替f([4])
。
This is a standard numpy feature, since you can call np.sin
as sin(array([4,5,6]))
, or as sin([4,5,6])
or as sin(4)
as well. 这是一个标准的numpy特性,因为你可以将np.sin
称为sin(array([4,5,6]))
,或者作为sin([4,5,6])
或sin(4)
。 I came up with this code, that works at least in simple cases: 我想出了这个代码,至少在简单的情况下是有效的:
def f(arr):
arr=asarray(arr)
if arr.shape is ():
print 'arr is a single float/int/etc'
arr = array([arr])
#process data as numpy array
#...
return arr
Is this the standard/correct way to do it? 这是标准/正确的方法吗?
I believe you are looking for np.atleast_1d
. 我相信你在寻找np.atleast_1d
。
>>> np.atleast_1d(5)
array([5])
>>> np.atleast_1d(np.arange(2))
array([0, 1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.