通过重复的日期时间索引进行聚合,并在pandas数据帧的列中使用不同的标识符

时间:2015-04-17 14:43:37

标签: python pandas

我有一个这种形式的数据框:

         value     identifier
2007-01-01  0.781611      55
2007-01-01  0.766152      56
2007-01-01  0.766152      57
2007-02-01  0.705615      55
2007-02-01  0.032134      56
2007-02-01  0.032134      57
2008-01-01  0.026512      55
2008-01-01  0.993124      56
2008-01-01  0.993124      57
2008-02-01  0.226420      55
2008-02-01  0.033860      56
2008-02-01  0.033860      57

我可以使用此answer按标识符对数据进行分组。

by_date = df.groupby(df.index.date)['value'].mean()
2007-01-01    0.771305
2007-02-01    0.256628
2008-01-01    0.670920
2008-02-01    0.098047

现在我想按月做一个盒子图,所以我想我可以按照它进行分组:

new_df = pd.DataFrame()
new_df['value'] = by_date
by_month = by_date.groupby(by_date.index.month)
aa = by_month.groupby(lambda x: x.month)
aa.boxplot(subplots=False)

如何在没有虚拟数据帧的情况下创建此箱图?

2 个答案:

答案 0 :(得分:2)

为了让groupby返回df而不是系列,请使用double subsription [[]]

by_date = df.groupby(df.index.date)[['value']].mean()

然后允许您按月分组并生成一个箱线图:

by_month = by_date.groupby(by_date.index.month)
by_month.boxplot(subplots=False)

使用double subsription是一个微妙的功能,并不是很明显,通常做df[col]将返回一列,但我们知道传递列col_list将返回一个df:{ {1}}展开时与df[col_list]相同,然后得出的结论是,如果我们执行以下操作,我们可以返回df:df[[col_a, col_b]]因为我们已经传递了包含单个元素的列表,这与我们传递标签以执行列索引的df[[col_a]]不同。

答案 1 :(得分:1)

在日期执行groupby时,您将索引从Timestamp转换为datetime.date。

>>> type(df.index[0])
pandas.tslib.Timestamp

>>> type(by_date.index[0])
datetime.date

如果将索引转换为期间,则可以轻松分组。

df.index = pd.DatetimeIndex(by_date.index).to_period('M')
>>> df.groupby(df.index).value.sum()
2007-01-01    2.313915
2007-02-01    0.769883
2008-01-01    2.012760
2008-02-01    0.294140
Name: value, dtype: float64
相关问题