其他分享
首页 > 其他分享> > 我如何在熊猫DataFrame中按月分组行?

我如何在熊猫DataFrame中按月分组行?

作者:互联网

我需要创建一些定时数据的箱形图,其中一个框代表每个月的原始数据.像这样:

enter image description here

现在,让我们尝试使用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)并应用汇总函数,例如中位数:

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

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

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

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

enter image description here

另外,我收到以下警告:

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

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

解决方法:

似乎您需要使用by关键字参数创建分组来为分层箱图的第一个期间创建新列:

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

graph

您还可以检查docs.

标签:pandas,dataframe,boxplot,python
来源: https://codeday.me/bug/20191026/1934747.html