[英]Aggregate by repeated values in a column in a data frame in pandas
I have a data frame as follows: 我有一个数据框,如下所示:
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
How can I aggregate by the value in the identifier column, like this: 如何按标识符列中的值进行汇总,如下所示:
value
2007-01-01 0.766 # (average of identifiers 55, 56 and 57 for this date)
2007-02-01 0.25
2008-01-01 etc...
2008-02-01
If your index is a datetime then you can access the .date
attribute, if not you can convert it using df.index = pd.to_datetime(df.index)
and then perform a groupby on the date and calc the mean: 如果索引是日期时间,则可以访问
.date
属性;如果不是,则可以使用df.index = pd.to_datetime(df.index)
对其进行转换,然后对日期进行df.index = pd.to_datetime(df.index)
,并计算均值:
In [214]:
df.groupby(df.index.date)['value'].mean()
Out[214]:
2007-01-01 0.771305
2007-02-01 0.256628
2008-01-01 0.670920
2008-02-01 0.098047
Name: value, dtype: float64
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.