Efficiently multiply elements of each row together

后端 未结 2 902
半阙折子戏
半阙折子戏 2020-12-07 04:27

Given a ndarray of size (n, 3) with n around 1000, how to multiply together all elements for each row, fast? The (inelegant) second solution below

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-07 05:05

    np.prod accepts an axis argument:

    np.prod(a, axis=1)
    

    With axis=1, the column-wise product is computed for each row.

    Sanity check

    assert np.array_equal(np.prod(a, axis=1), prod1(a))
    

    Performance

    17.6 µs ± 146 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    

    (1000x speedup)

提交回复
热议问题