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

前端 未结 6 982
你的背包
你的背包 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 03:02

    May I suggest, if your use-case is more limited to products, that you use the outer-product?

    e.g.:

    import numpy
    
    a = array([0, 1, 2])
    b = array([0, 1, 2, 3])
    
    numpy.outer(a,b)
    

    returns

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

    You can then apply other transformations:

    numpy.outer(a,b) + 1
    

    returns

    array([[1, 1, 1, 1],
           [1, 2, 3, 4],
           [1, 3, 5, 7]])
    

    This is much faster:

    >>> import timeit
    >>> timeit.timeit('numpy.array([[i*j for i in a] for j in b])', 'import numpy; a=numpy.arange(3); b=numpy.arange(4)')
    31.79583477973938
    
    >>> timeit.timeit('numpy.outer(a,b)', 'import numpy; a=numpy.arange(3); b=numpy.arange(4)')
    9.351550102233887
    >>> timeit.timeit('numpy.outer(a,b)+1', 'import numpy; a=numpy.arange(3); b=numpy.arange(4)')
    12.308301210403442
    

提交回复
热议问题