python - 使用 Python/Pandas/Numpy 计算图形/图中的循环数

标签 python pandas numpy dataframe matplotlib

如何使用 python/pandas/numpy 库从 matplotlib 中绘制的图表中找出 Y 值(速度)从 700 -800 RPM 到 1600 到 1800 RPM 上升和下降的次数,反之亦然。我使用 matplotlib 和 dataframe 绘制了该图。

预期输出应该是---> 速度上升的次数 = 2 & 下降 = 2 查看附图

下面附有图片/图表以提供更多说明

enter image description here

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

然后您将可以计算出上升或下降的次数。

关于python - 使用 Python/Pandas/Numpy 计算图形/图中的循环数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57082596/

相关文章:

python - 将 <input> 值传递给 Django View

python - 适用于 Python 的 Gekko 优化套件 - if3 始终 <0

python - 处理 pandas python 中的缺失数据

python - 如何将 Group By 系列转换为 Dataframe?

numpy - 奇数大小的 numpy 数组发送/接收

python - 计算两个数平方和的平方根的最有效方法是什么?

python - 如何将 NumPy 特征和标签数组转换为可用于 model.fit() 的 TensorFlow 数据集?

python - 在 Pandas 中重新索引并转换为 json

python - 使用matplotlib和mysql数据库创建散点图

Python 类派生自 pandas DataFrame,具有 list/DataFrame 属性