一个python函数,它接受标量或numpy数组作为参数

Tao*_*ozi 10 python arrays numpy function

正如标题所说,假设我想写一个符号函数(让我们暂时忘记符号(0)),显然我们期望sign(2)= 1和sign(array([ - 2,-2,2]))=阵列([ - 1,-1,1]).但是,以下函数不起作用,因为它无法处理numpy数组.

def sign(x):
    if x>0: return 1
    else: return -1
Run Code Online (Sandbox Code Playgroud)

下一个函数将无法工作,因为x只有一个形状成员,如果它只是一个数字.即使使用y = x*0 + 1这样的技巧,y也不会有[]方法.

def sign(x):
    y = ones(x.shape)
    y[x<0] = -1
    return y
Run Code Online (Sandbox Code Playgroud)

即使有另一个问题的想法(如何创建接受numpy数组,可迭代或标量的numpy函数?),当x是单个数字时,下一个函数将不起作用,因为在这种情况下x.shape和y.shape只是()和索引y是非法的.

def sign(x):
    x = asarray(x)
    y = ones(x.shape)
    y[x<0] = -1
    return y
Run Code Online (Sandbox Code Playgroud)

唯一的解决方案似乎是首先确定x是数组还是数字,但我想知道是否有更好的东西.如果你有很多像这样的小函数,编写分支代码会很麻烦.

dou*_*oug 3

我想知道这是否是您想要的矢量化函数:

>>> 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)
Run Code Online (Sandbox Code Playgroud)