2017-02-26 29 views
2

我需要创建一些定时数据的盒形图,其中一个框代表每个月的原始数据。事情是这样的:如何在pandas DataFrame中按月分组行?

enter image description here

现在,让我们尝试创建使用熊猫:

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(); 

这会创建一个代表每个月均值分布的框。

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 

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

回答

3

看来你需要period首先为分层创建新列箱线图使用by关键字参数创建分组:

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

graph

您还可以检查docs