how can I make a numpy function that accepts a numpy array, an iterable, or a scalar?

前端 未结 4 1033
死守一世寂寞
死守一世寂寞 2021-02-19 20:50

Suppose I have this:

def incrementElements(x):
   return x+1

but I want to modify it so that it can take either a numpy array, an iterable, or

4条回答
  •  甜味超标
    2021-02-19 21:54

    This is an old question, but here are my two cents.

    Although Pierre GM's answer works great, it has the---maybe undesirable---side effect of converting scalars to arrays. If that is what you want/need, then stop reading; otherwise, carry on. While this might be okay (and is probably good for lists and other iterables to return a np.array), it could be argued that for scalars it should return a scalar. If that's the desired behaviour, why not follow python's EAFP philosophy. This is what I usually do (I changed the example to show what could happen when np.asarray returns a "scalar"):

    def saturateElements(x):
        x = np.asarray(x)
        try:
            x[x>1] = 1
        except TypeError:
            x = min(x,1)
        return x
    

    I realize it is more verbose than Pierre GM's answer, but as I said, this solution will return a scalar if a scalar is passed, or a np.array is an array or iterable is passed.

提交回复
热议问题