0

My goal is to find the indexes of the local maxima and minima of the function in pandas or matplotlib.

Let us say we have a noisy signal with its local maxima and minima already plotted like in the following link:

https://stackoverflow.com/a/50836425/15934571

Here is the code (I just copy and paste it from the link above):

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.signal import argrelextrema

# Generate a noisy AR(1) sample

np.random.seed(0)
rs = np.random.randn(200)
xs = [0]
for r in rs:
    xs.append(xs[-1] * 0.9 + r)
df = pd.DataFrame(xs, columns=['data'])

n = 5  # number of points to be checked before and after

# Find local peaks

df['min'] = df.iloc[argrelextrema(df.data.values, np.less_equal,
                    order=n)[0]]['data']
df['max'] = df.iloc[argrelextrema(df.data.values, np.greater_equal,
                    order=n)[0]]['data']

# Plot results

plt.scatter(df.index, df['min'], c='r')
plt.scatter(df.index, df['max'], c='g')
plt.plot(df.index, df['data'])
plt.show()

So, I do not have any idea how to continue from this point and find indexes corresponding to the obtained local maxima and minima on the plot. Would appreciate any help!

1 Answers1

1

You use df['min'].notna(), it returns a dataframe in which the row of min is not nan. To find the index of local minima you can use the .loc method.

df.loc[df['min'].notna()].index

The output result for your example is:

Int64Index([0, 11, 21, 35, 43, 54, 67, 81, 105, 127, 141, 161, 168, 187], dtype='int64')

You can use the similar procedure to find local maximan.

Mohammadreza Riahi
  • 502
  • 1
  • 6
  • 20