How to get cumulative max indexes with numpy in Python?

I am trying to get the coordinates xand yall cumulative highs in a vector. I wrote naive for-loop, but I have a feeling that there is a way to do this with numpymore elegance.

Does anyone know of any features, masking methods, or single-line ones numpythat can do this?

Details should be described below:

# 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

+4
source share
1 answer

We could use np.maximum.accumulate-

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

, accumulative max , "" 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]

, , / .

+4

Source: https://habr.com/ru/post/1696329/


All Articles