代码之家  ›  专栏  ›  技术社区  ›  O.rka

如何在Python中使用numpy获得累计最大索引?

  •  6
  • O.rka  · 技术社区  · 6 年前

    我在试着 x y 向量中所有累积最大值的坐标。我写了一篇天真的 for-loop 但我觉得有办法 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

    1 回复  |  直到 6 年前
        1
  •  6
  •   Divakar    6 年前

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

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

    基本思想是 accumulative max 与当前元件进行比较时的值指示哪些元件位置负责“提升”运行最大值。负责任的是我们需要的指数 idx_max .由于我们使用的是浮动pt数,因此我们需要在其中加入一些公差 np.isclose

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

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

    但是,考虑到起始值,前面所做的假设使我们的代码更容易/紧凑/简短。