Numpy Vectorize Behavior

时间:2016-02-14 04:42:08

标签: python numpy

我正在尝试使用numpy.vectorize和这个lambda函数np.vectorize一个单周期的锯齿函数:

saw = lambda x: 0 if x < -2 or x > 2 else x

但是当我将矢量化saw应用于此数组时:

array([-4.    , -3.57894737, -3.15789474, -2.73684211, -2.31578947,
   -1.89473684, -1.47368421, -1.05263158, -0.63157895, -0.21052632,
    0.21052632,  0.63157895,  1.05263158,  1.47368421,  1.89473684,
    2.31578947,  2.73684211,  3.15789474,  3.57894737,  4.        ])

我明白了:

array([ 0,  0,  0,  0,  0, -1, -1, -1,  0,  0,  0,  0,  1,  1,  1,  0,  0,
    0,  0,  0])

这是怎么回事?

考虑到我使用Python 2.7和numpy 1.10.2

2 个答案:

答案 0 :(得分:2)

根据np.vectorize文档:

  

输出类型是通过计算输出的第一个元素来确定的   输入,除非指定

您的第一个输入元素生成int64类型的输出:

In [2]: data = np.array([-4.    , -3.57894737, -3.15789474, -2.73684211, -2.31578947,
   ...:    -1.89473684, -1.47368421, -1.05263158, -0.63157895, -0.21052632,
   ...:     0.21052632,  0.63157895,  1.05263158,  1.47368421,  1.89473684,
   ...:     2.31578947,  2.73684211,  3.15789474,  3.57894737,  4.        ])

In [3]: saw = lambda x: 0 if x < -2 or x > 2 else x

In [4]: saw_v = np.vectorize(saw)

In [5]: type(saw_v(data)[0])
Out[5]: numpy.int64

In [6]: type(saw_v(data[5:])[0])
Out[6]: numpy.float64

在向量化函数时,您必须指定otype

In [9]: saw_v_f = np.vectorize(saw, otypes=[np.float])

In [10]: type(saw_v_f(data)[0])
Out[10]: numpy.float64

In [11]: saw_v_f(data)
Out[11]: 
array([ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ,
       -1.89473684, -1.47368421, -1.05263158, -0.63157895, -0.21052632,
        0.21052632,  0.63157895,  1.05263158,  1.47368421,  1.89473684,
        0.        ,  0.        ,  0.        ,  0.        ,  0.        ])

答案 1 :(得分:-1)

似乎可以通过地图为我工作。

map(saw, x)

[0, 0, 0, 0, 0, -1.89473684, -1.47368421, -1.0526315799999999, -0.63157894999999997, -0.21052631999999999, 0.21052631999999999, 0.63157894999999997, 1.0526315799999999, 1.47368421, 1.89473684, 0, 0, 0, 0, 0]