如何在 pandas DataFrame 中按月对行进行分组?

How do I group rows by month in a pandas DataFrame?

我需要创建一些时间数据的箱线图,其中一个框表示每个月的原始数据。像这样:

现在让我们尝试使用 pandas:

创建它
matplotlib inline
import numpy as np
import pandas as pd

N_DAYS = 100
dates = pd.date_range('20130101', periods=N_DAYS)
df = pd.DataFrame(np.random.randn(N_DAYS,1), index=dates)

我可以按月重新采样(代码 M)并应用聚合函数,例如 median:

df.resample('M').median()

但是,我无法创建数据的箱线图:

df.resample('M').boxplot();

这将创建一个框,表示每个月的平均值分布。

此外,我收到以下警告:

FutureWarning: 
.resample() is now a deferred operation
You called boxplot(...) on this deferred object which materialized it into a dataframe
by implicitly taking the mean.  Use .resample(...).mean() instead

如何创建每个月原始数据的箱线图?

您似乎需要先为 period 创建新列,以便使用 by 关键字参数创建分组的分层箱线图:

df['per'] = df.index.to_period('M')
df.boxplot(by='per')

您还可以查看 docs