我怎样才能通过使用python/pandas/numpy库从matplotlib中绘制的图形中找出Y值(速度)从700 -800 RPM上升和下降到1600到1800 RPM的次数,反之亦然。我已经使用 matplotlib 和数据帧绘制了这个图。
预期输出应为--->速度上升次数 = 2 和下降 = 2 查看附图。
附上下面的图像/图表以进一步说明
在此处输入图像描述
fig = plt.figure(figsize =(18,10))
ax =plt.subplot(311)
plt.plot(df.speed)
ax.set_yticks([0, 500, 700, 1000, 1500, 1700, 2000])
ax.set_xlabel("Time (Seconds)")
ax.set_ylabel("Speed (RPM)")
plt.grid()
plt.show()
这是一个矢量化解决方案:
import pandas as pd
df = pd.DataFrame({'speed': [0,1600,0,1600,1600,1600,0,0,0]})
# Check if values are above or below a threshold
threshold = 1500
df['over_threshold'] = df['speed'] > threshold
# Compare to the previous row
# If over_threshold has changed,
# then you either went above or fell below the threshold
df['changed'] = df['over_threshold'] != df['over_threshold'].shift(1)
# First one has, by definition, has no previous value, so we should omit it
df = df.loc[1:,]
# Count how many times a row is newly above or below threshold
counts = df.loc[df['changed']].groupby('over_threshold').agg({'changed': 'count'})
counts.index = ["Down", "Up"]
counts.columns = ["Count"]
counts
# Count
#Down 2
#Up 2
然后,您将计算出您上升或下降的次数。
# state variables
decreasing = False
increasing = False
last_above = False
last_below = False
drop_count = 0
jump_count = 0
for rpm_str in df:
rpm = int(rpm_str) # Because OP indicated the data was a string
# Crossing threshold
if ((last_below or decreasing) and rpm < 700):
drop_count = drop_count + 1
decreasing = False
last_below = False
elif ((last_above or increasing) and rpm > 1600):
jump_count = jump_count + 1
increasing = False
last_above = False
if (last_above and rpm < 1600):
decreasing = True
increasing = False
elif (last_below and rpm > 700):
increasing = True
decreasing = False
# State
last_below = False
last_above = False
if (rpm < 700):
last_below = True
elif (rpm > 1600):
last_above = True
这不是一个完美的解决方案,可能会错过一些边缘情况,但您的数据看起来很正常
尝试以下代码:
y
是 y 数据 (rpm)lim
是周期开始的 rpm 量
cycles = 0
for i in range(len(y)):
if y[i] >= lim:
cycles += 1
while y[i] >= lim:
i += 1