如何在python2.7中使用vectorize numpy函数?

时间:2017-01-22 19:46:29

标签: python-2.7 numpy

我在ipython中尝试了以下代码:我想使用vectorize并给出函数prox(x,tau)。但是lambda中的第一个值总是两次。

In [32]: a = np.array([[ 1., 2.],[ 3., 4.]])
In [33]: def prox(x, tau):
    ...:     print x, tau
    ...:     if x >= tau:
    ...:         print "first"
    ...:         return x-tau
    ...:     if -tau <= x and x <= tau:
    ...:         print "second"
    ...:         return 0.0
    ...:     if x <= -tau:
    ...:         print "third"
    ...:         return x+tau

In [34]: b = np.vectorize(lambda x: prox(x, 2))(a[:,1:])
In [35]: b 
2.0 2
first
2.0 2
first
4.0 2
first

为什么第35行是两次打印相同的值? 2.0 2

1 个答案:

答案 0 :(得分:2)

如果您未指定otypes,则vectorize会使用第一个值执行测试计算,并使用它来确定它返回的数组的dtype。因此,第一项的双重评估。

通常额外的计算并不重要。不过要小心。如果初始计算返回一个整数(例如标量0),则返回的数组也将是整数,从而在后续计算中丢失任何浮点值。

有关详细信息,请查看vectorize的文档。

vectorize is indeterminate - 由非预期的整数otype产生的错误。我在其他SO问题中看到了这个错误。