Using Numpy Vectorize on Functions that Return Vectors

前端 未结 6 1724
生来不讨喜
生来不讨喜 2020-11-29 04:57

numpy.vectorize takes a function f:a->b and turns it into g:a[]->b[].

This works fine when a and b are scalars, but I can\'t t

6条回答
  •  温柔的废话
    2020-11-29 05:34

    A new parameter signature in 1.12.0 does exactly what you what.

    def f(x):
        return x * np.array([1,1,1,1,1], dtype=np.float32)
    
    g = np.vectorize(f, signature='()->(n)')
    

    Then g(np.arange(4)).shape will give (4L, 5L).

    Here the signature of f is specified. The (n) is the shape of the return value, and the () is the shape of the parameter which is scalar. And the parameters can be arrays too. For more complex signatures, see Generalized Universal Function API.

提交回复
热议问题