Pandas 重采样和箱线图(seaborn)

Pandas resample and boxplot (seaborn)

我有一个 pandas DataFrame,其中包含每隔几分钟记录一次的值。

import pandas as pd
import numpy as np
df = pd.DataFrame()
df['Time'] = pd.date_range("2018-01-01", periods=1000, freq="5Min")
df['Value'] = np.random.randint(1, 6, df.shape[0])

现在我想制作一个箱线图来显示每天的分布情况。通常,我会使用 resamplegroupby,但我无法将这些组反馈回 seaborn 以用于箱线图或执行其他一些统计数据。

现在我使用一种非常丑陋的形式将组 return 返回到 DataFrame 并将其翻转以将日期作为列:

daily = df.groupby(pd.Grouper(key='Time', freq='1D'))
df_days = daily['Value'].apply(lambda df: df.reset_index(drop=True)).unstack().transpose()

df_days 可以输入 seaborn.boxplot 以生成晶须图。

是否有更简单的方法来获取 DataFrame df_days

谢谢

由于您的数据已经是长格式,seaborn 是正确的选择。您可以使用 dt.normalize()dt.date 来获取日期:

sns.boxplot(y=df['Value'], x=df['Time'].dt.date)

输出: