如何创建"Weekly Boxplots"?

How to create "Weekly Boxplots"?

我有看起来像 this 的数据集。我有两个类别的月份数据,62 行,每个类别 31 行。我想在 y 轴上创建一个周数和月份的每周箱线图 [比如 01-12、02-12、03-12 等等]。

到目前为止,我已经想出了以下代码。

import seaborn as sns
import matplotlib.pyplot as plt

sns.set()
fig, ax = plt.subplots(figsize=(18,6))
df.index = pd.to_datetime(df.Timestamp)

sns.boxplot(x=df.index.week, y='Values', data=df, hue='Category', ax=ax)

通过使用 df.index.week,我没有得到预期的周值,而是给我一年中的周数,例如 this。

请指导?

您可以通过格式化 Date 列中的值在 df 中创建分组列:

date_range = pd.date_range(start='2013-12-01', end='2013-12-31').to_list()
df = pd.DataFrame(
    {
        "Date": date_range + date_range,
        "Values": np.random.randint(1000, 20000, 62),
        "Category": ["anti"] * 31 + ["pro"] * 31,
    }
)

使用 pandas.Series.dt.strftime 获取一年中的第几周 (%U) 和月份 (%m) 并加入 -:

df["week_month"] = df["Date"].dt.strftime("%U-%m")

(感谢更好的方法@Cameron Riddell

然后剧情:

sns.boxplot(x="week_month", y="Values", data=df, hue="Category")