我创建了一个随机游走数据集,计算了局部的最小和最大点,并使用matplotlib将它们绘制在图形上。我想知道Python中是否有一种方法可以使用数据点来创建一条线,并在与前两点相同的“方向”上针对每个周期扩展该线。参见下图。有什么想法可以做到吗?
谢谢您的帮助!
import random
from scipy.signal import argrelextrema
#create random walk
random.seed(1)
random_walk = list()
random_walk.append(-1 if random.random() < 0.5 else 1)
for i in range(1, 20):
movement = -1 if random.random() < 0.5 else 1
value = random_walk[i-1] + movement
random_walk.append(value)
df = pd.DataFrame(random_walk, columns=["data"])
n=3
# 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']
plt.scatter(df.index, df['min'], c='r')
plt.scatter(df.index, df['max'], c='g')
plt.plot(df.index, df['data'])
plt.plot(df['min'], '.r-')
plt.plot(df['max'], 'xb-')
plt.show()
print(df['min'])
print(df['min'])
答案 0 :(得分:1)
听起来您想使用两个(我将使用第一个和最后一个)局部最小值和最大值线性投影。因此,您必须确定这些点,然后拟合一个函数以线性地绘制它们,然后使用一组超出数据范围的点来绘制该函数:
{{1}}
结果:
如果您也想使用点(或所有点)的任何其他组合进行投影。您只需要更改正在使用的本地分钟数或最大值即可。如果需要,您还可以创建功能列表并全部绘制。
答案 1 :(得分:0)
如果我对您的理解正确,这可以解决问题:
import random
from scipy.signal import argrelextrema
#create random walk
random.seed(1)
random_walk = list()
random_walk.append(-1 if random.random() < 0.5 else 1)
for i in range(1, 20):
movement = -1 if random.random() < 0.5 else 1
value = random_walk[i-1] + movement
random_walk.append(value)
df = pd.DataFrame(random_walk, columns=["data"])
n=3
# 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']
mins = [(k, v) for k, v in list(df[['min']].dropna().to_dict().values())[0].items()]
maxs = [(k, v) for k, v in list(df[['max']].dropna().to_dict().values())[0].items()]
plt.scatter(df.index, df['min'], c='r')
plt.scatter(df.index, df['max'], c='g')
for previous, current in zip(mins, mins[1:]):
xs = [a for a,b in [previous, current]]
ys = [b for a,b in [previous, current]]
plt.plot(xs, ys)
for previous, current in zip(maxs, maxs[1:]):
xs = [a for a,b in [previous, current]]
ys = [b for a,b in [previous, current]]
plt.plot(xs, ys)
plt.plot(df.index, df['data'])
plt.plot(df['min'], '.r-')
plt.plot(df['max'], 'xb-')
plt.show()
结果: