Python 扩展平均时间增量
具有以下特征:Python 扩展平均时间增量,python,pandas,Python,Pandas,具有以下特征: 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_date
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组内时间戳列的扩展平均值,以反映行之间的平均时间增量(以秒为单位),因此输出为:
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())
如果我没弄错的话,让我们试试
df['delta']=df.groupby('id')['timestamp']].apply(lambda x:(x.diff().dt.seconds).expansing().mean())
?您的输出中的一些时间戳与您的输入不同。无论如何,我会使用@wwnde提到的代码。您可以将.fillna(0)
添加到链中。