Numpy quirk: Apply function to all pairs of two 1D arrays, to get one 2D array

前端 未结 6 972
你的背包
你的背包 2020-12-13 02:24

Let\'s say I have 2 one-dimensional (1D) numpy arrays, a and b, with lengths n1 and n2 respectively. I also have a functi

6条回答
  •  离开以前
    2020-12-13 02:47

    If F() works with broadcast arguments, definitely use that, as others describe.
    An alternative is to use np.fromfunction (function_on_an_int_grid would be a better name.) The following just maps the int grid to your a-b grid, then into F():

    import numpy as np
    
    def func_allpairs( F, a, b ):
        """ -> array len(a) x len(b):
            [[ F( a0 b0 )  F( a0 b1 ) ... ]
             [ F( a1 b0 )  F( a1 b1 ) ... ]
             ...
            ]
        """
        def fab( i, j ):
            return F( a[i], b[j] )  # F scalar or vec, e.g. gradient
    
        return np.fromfunction( fab, (len(a), len(b)), dtype=int )  # -> fab( all pairs )
    
    
    #...............................................................................
    def F( x, y ):
        return x + 10*y
    
    a = np.arange( 100 )
    b = np.arange( 222 )
    A = func_allpairs( F, a, b )
    # %timeit: 1000 loops, best of 3: 241 µs per loop -- imac i5, np 1.9.3
    

提交回复
热议问题