pandas将函数应用于按天分组的数据

时间:2017-04-19 18:38:20

标签: python pandas datetime group-by mean-square-error

我有一个如下所示的数据集:

date,value1,value2
2016-01-01 00:00:00,3,0
2016-01-01 01:00:00,0,0
2016-01-01 02:00:00,0,0
2016-01-01 03:00:00,0,0
2016-01-01 04:00:00,0,0
2016-01-01 05:00:00,0,0
2016-01-01 06:00:00,0,0
2016-01-01 07:00:00,0,2
2016-01-01 08:00:00,3,11
2016-01-01 09:00:00,14,14
2016-01-01 10:00:00,12,13
2016-01-01 11:00:00,11,13
2016-01-01 12:00:00,11,9
2016-01-01 13:00:00,17,21
2016-01-01 14:00:00,9,22
2016-01-01 15:00:00,10,9
2016-01-01 16:00:00,11,9
2016-01-01 17:00:00,8,8
2016-01-01 18:00:00,4,2
2016-01-01 19:00:00,5,7
2016-01-01 20:00:00,5,5
2016-01-01 21:00:00,3,4
2016-01-01 22:00:00,2,4
2016-01-01 23:00:00,2,4
2016-01-02 00:00:00,0,0
2016-01-02 01:00:00,0,0
2016-01-02 02:00:00,0,0
2016-01-02 03:00:00,0,0
2016-01-02 04:00:00,0,0
2016-01-02 05:00:00,0,0
2016-01-02 06:00:00,1,0
2016-01-02 07:00:00,0,0
2016-01-02 08:00:00,0,0
2016-01-02 09:00:00,0,0
2016-01-02 10:00:00,0,0
2016-01-02 11:00:00,0,0
2016-01-02 12:00:00,0,0
2016-01-02 13:00:00,1,0
2016-01-02 14:00:00,0,0
2016-01-02 15:00:00,0,0
2016-01-02 16:00:00,0,0
2016-01-02 17:00:00,0,0
2016-01-02 18:00:00,0,0
2016-01-02 19:00:00,0,0
2016-01-02 20:00:00,1,0
2016-01-02 21:00:00,0,0
2016-01-02 22:00:00,0,0
2016-01-02 23:00:00,0,0

我想要做的是计算每天value1和value2之间的rmse。 所以基本上,我想运行该功能31次(每天一次),输入将是当天的24个条目(每小时一个) 我尝试使用

rmse(df.groupby([df.index.day]).mean().value1, 
    df.groupby([df.index.day]).mean().value2)

但它给了我一个值,我想要的是一个包含每天rmse的列表,例如

daily_rmse = [rmse01_01, rmse01_02, ..., rmse01_31]

2 个答案:

答案 0 :(得分:1)

您无需继续重做rmse,并且需要在其中的每个元素上计算gb = df.groupby(df.index.date) mean_by_day = gb.mean() rmse_by_day = gb.std(ddof=0) ,而不是在均值序列上计算:

mean_by_day.value1

我怀疑您正在应用的RMSE公式完全等效于由元素数量标准化的标准偏差(不是元素数量 - 1,这是Pandas中的默认值)。

您现在应该可以访问std_by_day.value1mean_by_day来获取所需的值。

value1 value2 2016-01-01 5.416667 6.541667 2016-01-02 0.125000 0.000000 获得的值是

rmse_by_day

同样, value1 value2 2016-01-01 5.139039 6.422481 2016-01-02 0.330719 0.000000 我得到了

date

请注意,我们会使用索引的day字段,而不是factor,如果您的数据持续了几个月,则会重复该字段。

答案 1 :(得分:1)

使用sklearn s mean_squared_error

from sklearn.metrics import mean_squared_error

df.groupby(df.date.dt.date).apply(
    lambda x: mean_squared_error(x.value1, x.value2) ** .5)

date
2016-01-01    3.494043
2016-01-02    0.377964
dtype: float64