如何在Python中使用numpy获取累积最大索引?

问题描述 投票:4回答:1

我试图获得矢量中所有累积最大值的xy坐标。我写了一个天真的for-loop,但我有一种感觉,有一些方法来做更优雅的numpy

有没有人知道numpy中的任何功能,掩蔽技术或单行可以做到这一点?

细节应该由下图描述:

# Generate data
x = np.abs(np.random.RandomState(0).normal(size=(100)))
y = np.linspace(0,1,x.size)
z = x*y

# Get maximiums
idx_max = list()
val_max = list()

current = 0
for i,v in enumerate(z):
    if v > current:
        idx_max.append(i)
        val_max.append(v)
        current = v

# Plot them
with plt.style.context("seaborn-white"):
    fig, ax = plt.subplots(figsize=(10,3), ncols=2)
    ax[0].plot(z)
    ax[1].plot(z, alpha=0.618)
    ax[1].scatter(idx_max, val_max, color="black", edgecolor="maroon", linewidth=1.618)

enter image description here

python numpy indexing max cumulative-sum
1个回答
4
投票

我们可以利用np.maximum.accumulate -

idx_max = np.flatnonzero(np.isclose(np.maximum.accumulate(z),z))[1:]
val_max = z[idx_max]

基本思想是,当与当前元素相比时,这个accumulative max值表明哪个元素位置负责“提升”运行的最大值。负责任的是我们需要的指数idx_max。因为我们正在使用浮点数,我们需要在np.isclose中加入一些容差。

那个[1:]部分是因为起始电流值是0,所以是z[0]。因此,v > current部分不会将起始索引附加到输出中。要准确地说明它,应该是 -

current = 0
idx = np.flatnonzero(np.isclose(np.maximum.accumulate(z),z))
idx = idx[z[idx] > current]

但是,给定起始值,先前做出的假设使我们的代码更容易/紧凑/短。

© www.soinside.com 2019 - 2024. All rights reserved.