Using Numpy Vectorize on Functions that Return Vectors

前端 未结 6 1753
生来不讨喜
生来不讨喜 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:31

    The best way to solve this would be to use a 2-D NumPy array (in this case a column array) as an input to the original function, which will then generate a 2-D output with the results I believe you were expecting.

    Here is what it might look like in code:

    import numpy as np
    def f(x):
        return x*np.array([1, 1, 1, 1, 1], dtype=np.float32)
    
    a = np.arange(4).reshape((4, 1))
    b = f(a)
    # b is a 2-D array with shape (4, 5)
    print(b)
    

    This is a much simpler and less error prone way to complete the operation. Rather than trying to transform the function with numpy.vectorize, this method relies on NumPy's natural ability to broadcast arrays. The trick is to make sure that at least one dimension has an equal length between the arrays.

提交回复
热议问题