熊猫时间序列箱图

Fre*_*d S 10 python time-series boxplot 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()
Run Code Online (Sandbox Code Playgroud)

我知道我可以为当天制作一个额外的列,但我希望有适当的x轴标记和x限制功能(如in ts.plot()),因此能够使用日期时间索引会很棒.

没有为R/GGPLOT2类似的问题在这里,如果它有助于澄清我想要的东西.

Rut*_*ies 12

如果它是你的选择,我建议使用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)
Run Code Online (Sandbox Code Playgroud)

这使: 在此输入图像描述

请注意,我传递day of yeargrouper到seaborn,如果您的数据跨越多个年这是行不通的.然后你可以考虑这样的事情:

ts.index.to_series().apply(lambda x: x.strftime('%Y%m%d'))
Run Code Online (Sandbox Code Playgroud)

编辑,每3小时你可以使用它作为石斑鱼,但它只有在没有定义的分钟或更低时才有效.:

[(dt - datetime.timedelta(hours=int(dt.hour % 3))).strftime('%Y%m%d%H') for dt in ts.index]
Run Code Online (Sandbox Code Playgroud)


小智 8

(没有足够的代表对已接受的解决方案发表评论,因此请添加答案.)

接受的代码有两个小错误:(1)需要添加numpy导入和(2)nned交换语句中的参数xy参数boxplot.以下显示的图表.

import numpy as np
import pandas as pd
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)
Run Code Online (Sandbox Code Playgroud)