如何使用np.vectorize?

2024-09-27 09:37:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个函数来矢量化:

if x >= y, then x*y
else x/y

我的代码是:

def vector_function(x, y):

    if y >= x:
      return x*y
    else:
      return x/y
  
    vfunc = np.vectorize(vector_function)
    return vfunc
    
  raise NotImplementedError

但我得到了一个错误:

'>=' not supported between instances of 'int' and 'list'

有人能帮忙吗


Tags: 函数代码returnifdefnpfunction矢量化
2条回答

纯“矢量化”版本是:

def foo(x,y):
    return np.where(y>=x, x*y, x/y)

In [317]: foo(np.array([1,2,3,4]), 2.5)
Out[317]: array([2.5, 5. , 1.2, 1.6])

根据数组的大小,这比Stefans answer快2到10倍

我选择这种{}方法是因为它是最简单、最紧凑的{}广播方式。它可能不是最快的,这取决于/*的“成本”

问题是函数内部的vectorize-call

import numpy as np

# first define the function
def vector_function(x, y):
    if y >= x:
        return x * y
    else:
        return x / y

# vectorize it
vfunc = np.vectorize(vector_function)

# validation
print(vfunc([1, 2, 3, 4], 2.5)) # [2.5 5.  1.2 1.6]

但是,请注意,numpy.vectorize提供vectorize函数主要是为了方便,而不是为了性能。该实现本质上是一个for循环

相关问题 更多 >

    热门问题