我有一个数据集df,如下所示:
Value themes country date
-1.975767 Weather Brazil 2022-02-13
-0.540979 Fruits China 2022-02-13
-2.359127 Fruits China 2022-02-13
-2.815604 Corona China 2022-02-13
-0.712323 Weather UK 2022-02-13
-0.929755 Weather Brazil 2022-02-13我将themes+country分组以计算每个主题和国家组合的平均值和计数值(例如:天气、巴西或天气,英国)
df_calculations = df.groupby(["themes", "country"], as_index = False)["value"].mean()
df_calculations['count'] = df.groupby(["themes", "country"])["value"].count().tolist()然后,我将这个信息添加到一个新的表df_avg中,该表如下所示:
country type mean count last_checked_date
Brazil Weather x 2 2022-02-13 #same for all rows
Brazil Corona y 2022-02-13
China Corona z 1 2022-02-13
China Fruits s 2 2022-02-13但是,现在,在同一个原始df中还有新的行。
Value themes country date
-1.975560 Weather Brazil 2022-02-15
-0.540123 Fruits China 2022-02-16
-2.359234 Fruits China 2022-02-16
-2.359234 Corona UK 2022-02-16我想看看df行,谁的日期在last_checked_date之后。
然后,我想再次为每个组合计算一个新的平均值,但是使用我的df_avg表中的旧平均值和n值,而不是重新计算整个df。
我怎样才能做到这一点?
发布于 2022-02-26 19:39:33
请看这个:Calculate new mean from old mean
由于您正在维护一个计数(如果不是,这非常简单),您可以使用它和现有的平均值一起使用新的观察来计算更新的平均值。
https://stackoverflow.com/questions/71142498
复制相似问题