熊猫时间序列:平均时间戳列

时间:2018-06-11 10:20:42

标签: 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-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,我想要日期差异列表例如 - >列出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]

1 个答案:

答案 0 :(得分:4)

groupbydiffmean

一起使用
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

如果需要转换timedeltas,例如到days

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

编辑:

#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