使用numpy数组计算累积最小值 [英] Calculating cumulative minimum with numpy arrays

查看:303
本文介绍了使用numpy数组计算累积最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to calculate the "cumulative minimum" array--basically, the minimum value of an array up to each index such as:

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()函数可能更快,但是我也需要一个循环.

This works (it returns the correct array([ 5., 3., 3., 2., 1., 1., 1., 0.]) ), but I'd like to avoid the for loop if I can. I thought it might be faster to construct a 2-d array and use the np.amin() function, but I needed a loop for that as well.

推荐答案

对于任何2个参数的NumPy

For any 2-argument NumPy universal function, its accumulate method is the cumulative version of that function. Thus, numpy.minimum.accumulate is what you're looking for:

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

这篇关于使用numpy数组计算累积最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆