numpy中多个向量的逐个元素最小值 [英] Element-wise minimum of multiple vectors in numpy
问题描述
我知道在numpy中,我可以使用以下公式计算两个向量的逐元素最小值:
I know that in numpy I can compute the element-wise minimum of two vectors with
numpy.minimum(v1, v2)
如果我有一个等维向量列表,V = [v1, v2, v3, v4]
(但是列表,而不是数组)怎么办?接受numpy.minimum(*V)
不起作用.相反,首选的操作是什么?
What if I have a list of vectors of equal dimension, V = [v1, v2, v3, v4]
(but a list, not an array)? Taking numpy.minimum(*V)
doesn't work. What's the preferred thing to do instead?
推荐答案
*V
将起作用. np.minimum
是ufunc
,带有2个参数.
*V
works if V
has only 2 arrays. np.minimum
is a ufunc
and takes 2 arguments.
作为ufunc
,它具有.reduce
方法,因此可以重复应用于列表输入.
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.])
我怀疑np.min
方法更快,但这可能取决于数组和列表的大小.
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.])
ufunc
还有一个accumulate
,它可以向我们显示还原的每个阶段的结果.这不是很有趣,但是我可以调整输入来更改它.
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.]])
这篇关于numpy中多个向量的逐个元素最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!