python - Pandas 中的时间序列箱线图

标签 python pandas 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()

我知道我可以为当天制作一个额外的专栏,但我想要适当的 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)

给出: enter image description here

请注意,我将 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/

相关文章:

machine-learning - 我们可以使用预测值进行预测吗?

python - 如何使用 zip 连接深层嵌套列表的最里面的元素

python - 如果该行为空,则用另一列的值更新一列

datetime - R:将 mts 转换为具有时间索引的非时间序列数据帧的最佳方法

python - Pandas 如何将数组放在单个数据框单元格中?

python - pandas.DataFrame.loc ,在新列中标记数据

R:子集一个动物园对象?

python - 向量化 numpy 折扣计算

python - 在 Python 2.7.2 中设置端口以与 Arduino Uno 一起使用

python - 将字符串输出转换为 JSON