我怎样才能使一个接受numpy的阵列,可迭代,或者一个标量函数numpy的? [英] how can I make a numpy function that accepts a numpy array, an iterable, or a scalar?
问题描述
假设我有这样的:
def incrementElements(x):
return x+1
但我要修改它,以便它可以采取无论是numpy的阵列,可迭代,或者一个标量,促进了论证到numpy的数组,并添加1到每个元素。
but I want to modify it so that it can take either a numpy array, an iterable, or a scalar, and promote the argument to a numpy array and add 1 to each element.
我怎么能这样做呢?我想我可以测试参数类,但似乎像一个坏主意。如果我这样做:
How could I do that? I suppose I could test argument class but that seems like a bad idea. If I do this:
def incrementElements(x):
return numpy.array(x)+1
它工作正常的阵列或iterables而不是标量。这里的问题是, numpy.array(X)
标量点¯x产生一个由numpy的阵列包含一些奇怪的对象,但不是一个真正的数组;如果我添加一个标量它,结果被降级为标量。
it works properly on arrays or iterables but not scalars. The problem here is that numpy.array(x)
for scalar x produces some weird object that is contained by a numpy array but isn't a "real" array; if I add a scalar to it, the result is demoted to a scalar.
推荐答案
您可以尝试
def incrementElements(x):
x = np.asarray(x)
return x+1
np.asarray(X)
是 np.array相当于(X,复制= FALSE)
,这意味着一个标量或可迭代将被改造为 ndarray
,但如果 X
已经在 ndarray
,其数据将不会被复制。
np.asarray(x)
is the equivalent of np.array(x, copy=False)
, meaning that a scalar or an iterable will be transformed to a ndarray
, but if x
is already a ndarray
, its data will not be copied.
如果您通过一个标量并希望 ndarray
作为输出(不是标),你可以使用:
If you pass a scalar and want a ndarray
as output (not a scalar), you can use:
def incrementElements(x):
x = np.array(x, copy=False, ndmin=1)
return x
的 ndmin = 1
参数将迫使阵列至少有一个尺寸。使用 ndmin = 2
至少2的尺寸,等等。您还可以使用它的等效 np.atleast_1d
(或 np.atleast_2d
为2D版...)
The ndmin=1
argument will force the array to have at least one dimension. Use ndmin=2
for at least 2 dimensions, and so forth. You can also use its equivalent np.atleast_1d
(or np.atleast_2d
for the 2D version...)
这篇关于我怎样才能使一个接受numpy的阵列,可迭代,或者一个标量函数numpy的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!