python - 扩展时间增量平均值

标签 python pandas

具有以下 DF:

df = pd.DataFrame({'id':[1,1,1,2,2,2,2],
'timestamp':['2020-09-01 18:14:35','2020-09-01 18:14:39',
'2020-09-01 18:14:40','2020-09-01 02:09:22','2020-09-01 02:09:35',
'2020-09-01 02:09:53','2020-09-01 02:09:57']})

df['timestamp'] = pd.to_datetime(df.timestamp)
print(df.head())

   id           timestamp
0   1 2020-09-01 18:14:35
1   1 2020-09-01 18:14:39
2   1 2020-09-01 18:14:40
3   2 2020-09-01 02:09:22
4   2 2020-09-01 02:09:35

我想计算每个 id 组内时间戳列的扩展平均值,以反射(reflect)行之间的平均时间增量(以秒为单位),因此输出将是:

   id           timestamp  delta
0   1 2020-09-01 18:14:35      0 - first row is always 0
1   1 2020-09-01 18:14:39      4 - (0 + 4) / 1
2   1 2020-09-01 18:14:41      3 - (0  + 4 + 2) / 2
3   2 2020-09-01 02:09:22      0 - first row is always 0
4   2 2020-09-01 02:09:34     12 - (0 + 12) / 1 

我已经尝试过:

df.groupby('id')['timestamp'].apply(lambda x: x.mean())

但输出是整个组的平均值。 :(

最佳答案

对具有特定 ID 的不同组中的每个连续行使用 timedelta(以秒为单位)。获取扩展均值。

df['delta']=df.groupby('id')['timestamp'].apply(lambda x: (x.diff().dt.seconds).expanding().mean())

关于python - 扩展时间增量平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65520095/

相关文章:

Python数据框按列分组并用百分比创建新列

python - 如何按值删除列?

python - Pandas/Numpy 组值变化和导数值变化高于/低于 0

python - Numpy:创建一个掩码数组来选择矩形

python - 多维数组中列的平方和的平方根

python - Django - URL 文件中的语法错误

python - 在Python中水平合并具有不同分隔符和列的CSV的最快方法?

python - 如何卸载预提交

python - 为什么使用 Celery 而不是 RabbitMQ?

python - Pandas 分组重量递减