Pandas 计算每小时平均值

3

我有一个数据框,其中时间是与数据集相关的浮点数:

 Time            Value
-47.88333         90
-46.883333        23
-45.900000        66
-45.883333        87
-45.383333        43

时间列范围从-48到0。 我希望的是计算每隔半小时从-47.5到-.5的平均值。例如:

-47.5是所有落在-48和-47之间的值的平均值,-46.5是所有落在-47和-46之间的值的平均值。如果没有值,我想继续使用之前的平均值。

最终输出结果如下:

 Time            Value
-47.5             90
-46.5             23
-45.5             65.33
-44.5             65.33
-43.5             65.33

由于时间列不是datetime对象,所以这是否需要成为自定义函数?


那个时间值代表什么?-46.5表示在某个时间点之前的46小时30分钟? - Marc B
2个回答

3
您可以很容易地使用groupby来实现这一点:
(df.groupby(df.Time.apply(lambda x: np.floor(x) + 0.5))
   .mean()
   .Value
   .reindex(np.arange(-47.5, -42.5))
   .ffill())

Time
-47.5    90.000000
-46.5    23.000000
-45.5    65.333333
-44.5    65.333333
-43.5    65.333333
Name: Value, dtype: float64

2

使用pd.cut对时间变量进行分组:

#change the bins arg to modify the size of the bins
df.loc[:, 'TimeBin'] = pd.cut(df.Time, bins=[i for i in range (-48, 0)])
#groupby the time bin and take the mean:
df[['TimeBin', 'Value']].groupby('TimeBin').mean()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接