Python Pandas timeseries:时间戳列的平均值

Python Pandas timeseries:时间戳列的平均值,python,pandas,Python,Pandas,我有一个数据框,看起来像这样: ID Date 16911 2017-04-15 16911 2017-04-25 16911 2017-04-27 16911 2017-05-08 16911 2017-05-20 16911 2017-05-25 16911 2017-08-08 16911 2017-08-11 16911 2017-08-24 16912 2017-04-15 16912 2017-04-25 16812 2017

我有一个数据框,看起来像这样:

ID      Date
16911   2017-04-15
16911   2017-04-25
16911   2017-04-27
16911   2017-05-08
16911   2017-05-20
16911   2017-05-25
16911   2017-08-08
16911   2017-08-11
16911   2017-08-24
16912   2017-04-15
16912   2017-04-25
16812   2017-04-27
16812   2017-05-08
16812   2017-05-20
16812   2017-05-25
16812   2017-08-08
16812   2017-08-11
对日期进行排序后,我想找到时间戳之间的差异,并找到每个ID的平均值

而且

假设对于ID-16911,我想要eg->list a的日期差异列表

16911   2017-04-15
16911   2017-04-25
difference between the above two dates is 10, so a is
a = [10]

16911   2017-04-25
16911   2017-04-27
difference between the above two dates is 2, so a is
a=[10,2]

16911   2017-04-27
16911   2017-05-08
difference between the above two dates is 11(assuming), so a is
a=[10,2,11]
因此,最终输出应为:

ID      Average_Day Diff
16911   3 days      [10,2,11]
与和
平均值一起使用

df = df.groupby('ID')['Date'].apply(lambda x: x.diff().mean()).reset_index()
print (df)
      ID             Date
0  16812 21 days 04:48:00
1  16911 16 days 09:00:00
2  16912 10 days 00:00:00
如果需要将时间增量转换为

df = df.groupby('ID')['Date'].apply(lambda x: x.diff().mean().days).reset_index()
print (df)
      ID  Date
0  16812    21
1  16911    16
2  16912    10
编辑:


我还有一个问题,对于每个id,我能否得到两个日期之间的差异并将其存储在一个列表中(当然,对于每个id)?@SriramArvindLakshmanakumar-您能否将预期的输出添加到问题中?我已在问题中添加了输出。
#create difference column per ID
df['new'] = df.groupby('ID')['Date'].diff().dt.days
#remove NaT rows (first for each group)
df = df.dropna(subset=['new'])
#convert to integers
df['new'] = df['new'].astype(int)
#aggreagte lists and mean
df = df.groupby('ID', sort=False)['new'].agg([('val', lambda x: x.tolist()),('avg', 'mean')])
print (df)

ID                                          
16911  [10, 2, 11, 12, 5, 75, 3, 13]  16.375
16912                           [10]  10.000
16812             [11, 12, 5, 75, 3]  21.200