使用 Pandas 和 Matplotlib 缺少数据和绘图

Missing Data and Graphing with Pandas and Matplotlib

我希望我的 matplotlib 图在 x 轴上将我的 df 的 DateTimeIndex 显示为连续计数数据(以秒为单位),在 y 轴上显示我的 df 的加载数据。然后我想将它与 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。我想我可能完全以错误的方式解决这个问题。想法?

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

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

这是否符合您的预期?