查找日期列表中的日期差异[熊猫]

时间:2016-02-03 01:43:32

标签: python pandas

假设以下数据集已排序日期列表:

dates=pd.DataFrame(data={'client':['1','2'],
                         'date':[['2012-3-10','2012-3-11','2012-3-12','2012-3-13','2012-3-14'],
                                 ['2012-3-12','2012-3-13','2012-3-16','2012-3-23']]})

sample dataset

我想找到以天为单位的平均日期差异 因此,例如,对于Client '2'Average Timelag将为2.75

2 个答案:

答案 0 :(得分:2)

从:

开始
  client                                               date
0      1  [2012-3-10, 2012-3-11, 2012-3-12, 2012-3-13, 2...
1      2       [2012-3-12, 2012-3-13, 2012-3-16, 2012-3-23]

你可以

dates.groupby('client')['date'].apply(lambda x: [i / np.timedelta64(1, 'D') for i in np.diff([pd.to_datetime(c) for c in x])[0]])

获取timedelta中的days

client
1    [1.0, 1.0, 1.0, 1.0]
2         [1.0, 3.0, 7.0]

dates.groupby('client')['date'].apply(lambda x: np.mean([i / np.timedelta64(1, 'D') for i in np.diff([pd.to_datetime(c) for c in x])[0]]))

代表mean

client
1    1.000000
2    3.666667

答案 1 :(得分:0)

这是重复:

Difference between two dates?

看起来你可以使用datetime模块来解析你导入支持代数的对象的日期和/或时间字符串。

https://docs.python.org/2/library/datetime.html

干杯

相关问题