繁体   English   中英

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

[英]Aggregate by repeated datetime index with different identifiers in a column on a pandas dataframe

我有这种形式的数据框:

         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

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

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)

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

为了让groupby返回df而不是Series,请使用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: df[col_list] ,当扩展时它是与df[[col_a, col_b]]相同df[[col_a, col_b]]这导致我们可以返回一个df的结论,如果我们执行以下操作: df[[col_a]]因为我们已经传递了一个包含单个元素的列表,这不是与df[col_a]相同,我们传递了一个标签来执行列索引。

在日期执行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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM