Python 使用numpy数组计算累积最小值

Python 使用numpy数组计算累积最小值,python,arrays,numpy,Python,Arrays,Numpy,我想计算“累积最小值”数组——基本上是数组的最小值,直到每个索引,例如: import numpy as np nums = np.array([5.,3.,4.,2.,1.,1.,2.,0.]) cumulative_min = np.zeros(nums.size, dtype=float) for i,num in enumerate(nums): cumulative_min[i] = np.min(nums[0:i+1]) 这是可行的(它返回正确的数组([5,3,3,2,1,

我想计算“累积最小值”数组——基本上是数组的最小值,直到每个索引,例如:

import numpy as np
nums = np.array([5.,3.,4.,2.,1.,1.,2.,0.])
cumulative_min = np.zeros(nums.size, dtype=float)
for i,num in enumerate(nums):
    cumulative_min[i] = np.min(nums[0:i+1])
这是可行的(它返回正确的数组([5,3,3,2,1,1,1,0])
),但如果可以的话,我想避免for循环。我认为构建二维数组并使用np.amin()函数可能会更快,但我也需要一个循环。

创建一个矩阵,其中下三角(
np.tril
)填充数组
nums
和上三角(
np.triu
,第二个参数为1,因此对角线保持自由)用数组的最大值填充。(编辑:数组的第一个元素不是最大值,而是更好的方式。->注释)

Out:

(array([[ 5.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 5.,  3.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 5.,  3.,  4.,  0.,  0.,  0.,  0.,  0.],
       [ 5.,  3.,  4.,  2.,  0.,  0.,  0.,  0.],
       [ 5.,  3.,  4.,  2.,  1.,  0.,  0.,  0.],
       [ 5.,  3.,  4.,  2.,  1.,  1.,  0.,  0.],
       [ 5.,  3.,  4.,  2.,  1.,  1.,  2.,  0.],
       [ 5.,  3.,  4.,  2.,  1.,  1.,  2.,  0.]]),
 array([[ 0.,  5.,  5.,  5.,  5.,  5.,  5.,  5.],
       [ 0.,  0.,  5.,  5.,  5.,  5.,  5.,  5.],
       [ 0.,  0.,  0.,  5.,  5.,  5.,  5.,  5.],
       [ 0.,  0.,  0.,  0.,  5.,  5.,  5.,  5.],
       [ 0.,  0.,  0.,  0.,  0.,  5.,  5.,  5.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  5.,  5.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  5.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]]))
array([ 5.,  3.,  3.,  2.,  1.,  1.,  1.,  0.])
现在取每行的最小值:

(A+B).min(axis=1)
Out:

(array([[ 5.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 5.,  3.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 5.,  3.,  4.,  0.,  0.,  0.,  0.,  0.],
       [ 5.,  3.,  4.,  2.,  0.,  0.,  0.,  0.],
       [ 5.,  3.,  4.,  2.,  1.,  0.,  0.,  0.],
       [ 5.,  3.,  4.,  2.,  1.,  1.,  0.,  0.],
       [ 5.,  3.,  4.,  2.,  1.,  1.,  2.,  0.],
       [ 5.,  3.,  4.,  2.,  1.,  1.,  2.,  0.]]),
 array([[ 0.,  5.,  5.,  5.,  5.,  5.,  5.,  5.],
       [ 0.,  0.,  5.,  5.,  5.,  5.,  5.,  5.],
       [ 0.,  0.,  0.,  5.,  5.,  5.,  5.,  5.],
       [ 0.,  0.,  0.,  0.,  5.,  5.,  5.,  5.],
       [ 0.,  0.,  0.,  0.,  0.,  5.,  5.,  5.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  5.,  5.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  5.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]]))
array([ 5.,  3.,  3.,  2.,  1.,  1.,  1.,  0.])
对于任何2参数NumPy,其方法是该函数的累积版本。因此,
numpy.minimum.acculate
就是您要寻找的:

>>> numpy.minimum.accumulate([5,4,6,10,3])
array([5, 4, 4, 4, 3])

您也可以对上三角中的值使用无穷大,而不是
nums.max()
@Blckknght尝试过它,乍一看不起作用,所以我取了最大值。。。我再试一次,infinity将
0
-部分
B
更改为
NaN
nice。我不知道三角形函数,非常有用。啊,你说得对。我不认为
0*inf
是一个问题,但它确实是一个问题。您可以使用
nums[0]
,因为这始终是一个潜在的最小值。实际上,使用
max
并不是很糟糕(它只在已经
O(N^2)
的算法上添加了一个O(N)`项。@Blckknght
nums[0]
是个好主意……我将改变它……谢谢!