实数maxima/minima 2minima/maxima

Real maxima/minima between 2 minima/maxima

如何去除相应最大值/最小值之间较小的最大值和较大的最小值?我总是希望最大值跟随最小值,反之亦然,最小值跟随最大值。

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()

你可以做类似的事情。我们将 df 分组为连续最大值之间的部分,然后对于每个部分只取最小的最小值。然后我们按最小值分组,只为每个部分取最高的最大值:

max_grouper = (~df['max'].isna()).cumsum()
df['min2'] = (df.groupby(max_grouper, group_keys = False)
                .apply (lambda g: g['min'].where(g['min'] == g['min'].min()))
    )
min_grouper = (~df['min2'].isna()).cumsum()
df['max2'] = (df.groupby(min_grouper, group_keys = False)
                .apply (lambda g: g['max'].where(g['max'] == g['max'].max()))
    )

我将“修剪后的”最小值和最大值放入 'min2' 和 'max2' 列。我们使用黄色和蓝色绘制它们,同时保持原始的红色和绿色:

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

输出:

红色的是'min2'中不存在的。在这种情况下,没有 'max' 点被移除