重载一个浮动到numpy的数组 [英] overloading a float to a numpy array
问题描述
我有一个函数,处理一维数组numpy的,像这样的:
I have a function, processing a 1D numpy array, like this:
def f(arr):
arr=asarray(arr)
#process data as numpy array
#...
return arr
使用 asarray
我允许调用函数列表作为 F([4,5,6])
。现在,我想过载的说法也为单精度浮点,这样我就可以使用 F(4)
而不是的F([ 4])
。
With asarray
I allow to call the function with a list as 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])
.
这是一个标准的numpy的功能,因为你可以叫 np.sin
为罪(阵列([4,5,6]))
,或作为罪([4,5,6])
或罪(4)
为好。我想出了这个code,在简单情况下工作至少为:
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. 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?
推荐答案
我相信你正在寻找的 np.atleast_1d
。
I believe you are looking for np.atleast_1d
.
>>> np.atleast_1d(5)
array([5])
>>> np.atleast_1d(np.arange(2))
array([0, 1])
这篇关于重载一个浮动到numpy的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!