Parameters to numpy's fromfunction

前端 未结 6 1797
终归单人心
终归单人心 2020-11-30 07:37

I haven\'t grokked the key concepts in numpy yet.

I would like to create a 3-dimensional array and populate each cell with the result of a function call

6条回答
  •  执念已碎
    2020-11-30 08:13

    Here's my take on your problem:

    As mentioned by Chris Jones the core of the solution is to use np.vectorize.

    # Define your function just like you would
    def sum_indices(x, y, z):
        return x + y + z
    
    # Then transform it into a vectorized lambda function
    f = sum_indices
    fv = np.vectorize(f)
    

    If you now do np.fromfunction(fv, (3, 3, 3)) you get this:

    array([[[0., 1., 2.],
            [1., 2., 3.],
            [2., 3., 4.]],
    
           [[1., 2., 3.],
            [2., 3., 4.],
            [3., 4., 5.]],
    
           [[2., 3., 4.],
            [3., 4., 5.],
            [4., 5., 6.]]])
    

    Is this what you wanted?

提交回复
热议问题