【问题标题】:Missing Data and Graphing with Pandas and MatplotlibPandas 和 Matplotlib 缺失数据和绘图
【发布时间】:2021-03-21 04:16:48
【问题描述】:

我希望我的 matplotlib 图将我的 df 的 DateTimeIndex 显示为 x 轴上的连续计数数据(以秒为单位),我的 df 的加载数据在 y 轴上。然后我想将它与 scipy.signal find_peaks 结果(具有连续秒的 x 轴)重叠。我的数据不是连续的(现实世界的数据),尽管它确实有几秒钟的频率。

代码

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

# Create Sample Dataset
df = pd.DataFrame([['2020-07-25 09:26:28',2],['2020-07-25 09:26:29',10],['2020-07-25 09:26:32',203],['2020-07-25 09:26:33',30]], 
                      columns = ['Time','Load'])

df['Time'] = pd.to_datetime(df['Time'])
df = df.set_index("Time")
print(df)

# Try to solve the problem
rng = pd.date_range(df.index[0], df.index[-1], freq='s')
print(rng)

peaks, _ = signal.find_peaks(df["Load"])
plt.plot(rng, df["Load"])
plt.plot(peaks, df["Load"][peaks], "x")
plt.plot(np.zeros_like(df["Load"]), "--", color="gray")
plt.show()

此代码不起作用,因为 rng 的长度为 6,而 df 的长度为 4。我想我可能完全走错了路。想法?

【问题讨论】:

    标签: python pandas matplotlib scipy datetimeindex


    【解决方案1】:

    你真的很接近 - 我认为你可以通过用你的范围重新索引你的 df 来得到你想要的。例如:

    df = df.reindex(rng).fillna(0)
    peaks, _ = signal.find_peaks(df["Load"])
    ...
    

    这符合您的预期吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 2015-09-10
      • 2018-06-01
      • 1970-01-01
      • 2014-07-27
      • 2017-03-21
      相关资源
      最近更新 更多