我如何为 pandas 时间序列创建箱线图,其中我每天都有一个框?
每小时数据的示例数据集,其中一个框应包含 24 个值:
import pandas as pd
n = 480
ts = pd.Series(randn(n),
index=pd.date_range(start="2014-02-01",
periods=n,
freq="H"))
ts.plot()
我知道我可以为当天制作一个额外的专栏,但我想要适当的 x 轴标签和 x 限制功能(如 ts.plot()
),所以能够使用日期时间索引会很棒。
R/ggplot2 也有类似的问题 here ,如果它有助于澄清我想要什么。
最佳答案
如果您可以选择,我建议您使用 Seaborn ,它是 Matplotlib 的包装器。您可以通过遍历时间序列中的组来自己完成,但这需要更多工作。
import pandas as pd
import numpy as np
import seaborn
import matplotlib.pyplot as plt
n = 480
ts = pd.Series(np.random.randn(n), index=pd.date_range(start="2014-02-01", periods=n, freq="H"))
fig, ax = plt.subplots(figsize=(12,5))
seaborn.boxplot(ts.index.dayofyear, ts, ax=ax)
给出:
请注意,我将 day of year
作为 grouper
传递给 seaborn,如果您的数据跨越多年,这将不起作用。然后你可以考虑这样的事情:
ts.index.to_series().apply(lambda x: x.strftime('%Y%m%d'))
编辑,对于 3 小时,您可以将其用作石斑鱼,但它仅在没有分钟或更短的定义时才有效。 :
[(dt - datetime.timedelta(hours=int(dt.hour % 3))).strftime('%Y%m%d%H') for dt in ts.index]
关于python - Pandas 中的时间序列箱线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26507404/