Element-wise minimum of multiple vectors in numpy

后端 未结 2 725
长发绾君心
长发绾君心 2021-01-12 03:26

I know that in numpy I can compute the element-wise minimum of two vectors with

numpy.minimum(v1, v2)

What if I have a list of vectors of e

2条回答
  •  北海茫月
    2021-01-12 03:56

    *V works if V has only 2 arrays. np.minimum is a ufunc and takes 2 arguments.

    As a ufunc it has a .reduce method, so it can apply repeated to a list inputs.

    In [321]: np.minimum.reduce([np.arange(3), np.arange(2,-1,-1), np.ones((3,))])
    Out[321]: array([ 0.,  1.,  0.])
    

    I suspect the np.min approach is faster, but that could depend on the array and list size.

    In [323]: np.array([np.arange(3), np.arange(2,-1,-1), np.ones((3,))]).min(axis=0)
    Out[323]: array([ 0.,  1.,  0.])
    

    The ufunc also has an accumulate which can show us the results of each stage of the reduction. Here's it's not to interesting, but I could tweak the inputs to change that.

    In [325]: np.minimum.accumulate([np.arange(3), np.arange(2,-1,-1), np.ones((3,))])
         ...: 
    Out[325]: 
    array([[ 0.,  1.,  2.],
           [ 0.,  1.,  0.],
           [ 0.,  1.,  0.]])
    

提交回复
热议问题