接受作为一个参数一个标量或numpy的阵列Python函数 [英] A python function that accepts as an argument either a scalar or a numpy array

查看:254
本文介绍了接受作为一个参数一个标量或numpy的阵列Python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,假设我想写一个符号函数(让我们忘了标志(0)现在),很明显,我们希望签(2)= 1,符号(阵列([ - 2,-2,2] ))=阵列([ - 1,-1,1])。下面的函数将不但是工作,因为它不能处理numpy的数组。

As the title says, suppose I want to write a sign function (let's forget sign(0) for now), obviously we expect sign(2) = 1 and sign(array([-2,-2,2])) = array([-1,-1,1]). The following function won't work however, because it can't handle numpy arrays.

def sign(x):
    if x>0: return 1
    else: return -1

接下来的功能将不起作用或者因为X没有形状成员,如果它只是一个数字。即使有些把戏像Y = X * 0 + 1时,Y不会有[]的方法。

The next function won't work either since x doesn't have a shape member if it's just a single number. Even if some trick like y = x*0 + 1 is used, y won't have a [] method.

def sign(x):
    y = ones(x.shape)
    y[x<0] = -1
    return y

即使有另一个问题的想法(<一个href=\"http://stackoverflow.com/questions/12653120/how-can-i-make-a-numpy-function-that-accepts-a-numpy-array-an-iterable-or-a-sc\">how我可以接受一个numpy的阵列,可迭代,或者一个标量函数numpy的?中),当x是一个单一的数字下一个功能将无法正常工作,因为在这种情况下x.shape和y.shape是只是()和索引y是非法的。

Even with the idea from another question(how can I make a numpy function that accepts a numpy array, an iterable, or a scalar?), the next function won't work when x is a single number because in this case x.shape and y.shape are just () and indexing y is illegal.

def sign(x):
    x = asarray(x)
    y = ones(x.shape)
    y[x<0] = -1
    return y

唯一的解决办法似乎是第一个决定,如果x是一个数组或一个数字,但我想知道是否有更好的东西。枝写作code会很麻烦,如果你有大量的小功能,如这一点。

The only solution seems to be that first decide if x is an array or a number, but I want to know if there is something better. Writing branchy code would be cumbersome if you have lots of small functions like this.

推荐答案

我不知道这是一个 矢量功能您想:

i wonder if it's a vectorized function that you want:

>>> import numpy as NP

>>> def fnx(a):
        if a > 0:
            return 1
        else:
            return -1

>>> vfnx = NP.vectorize(fnx)

>>> a = NP.random.randint(1, 10, 5)
array([4, 9, 7, 9, 2])

>>> a0 = 7

>>> vfnx(a)
array([1, 1, 1, 1])

>>> vfnx(a0)
array(1)

这篇关于接受作为一个参数一个标量或numpy的阵列Python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆