简体   繁体   English

计算多个日期之间的平均天数

[英]Calculate Average Number of Days Between Multiple Dates

Let's say I have the following data frame.假设我有以下数据框。 I want to calculate the average number of days between all the activities for a particular account.我想计算特定帐户的所有活动之间的平均天数。

在此处输入图片说明

Below is my desired result:下面是我想要的结果:

在此处输入图片说明

Now I know how to calculate the number of days between two dates with the following code.现在我知道如何使用以下代码计算两个日期之间的天数。 But I don't know how to calculate what I am looking for across multiple dates.但我不知道如何计算我在多个日期中寻找的内容。

from datetime import date

d0 = date(2016, 8, 18)
d1 = date(2016, 9, 26)
delta = d0 - d1
print delta.days

I would do this as follows in pandas (assuming the Date column is a datetime64):我会在熊猫中按如下方式执行此操作(假设日期列是 datetime64):

In [11]: df
Out[11]:
  Account Activity       Date
0       A        a 2015-10-21
1       A        b 2016-07-07
2       A        c 2016-07-07
3       A        d 2016-09-14
4       A        e 2016-10-12
5       B        a 2015-11-24
6       B        b 2015-12-30

In [12]: df.groupby("Account")["Date"].apply(lambda x: x.diff().mean())
Out[12]:
Account
A   89 days 06:00:00
B   36 days 00:00:00
Name: Date, dtype: timedelta64[ns]

If your dates are in a list:如果您的日期在列表中:

>>> from datetime import date
>>> dates = [date(2015, 10, 21), date(2016, 7, 7), date(2016, 7, 7), date(2016, 9, 14), date(2016, 10, 12), date(2016, 10, 12), date(2016, 11, 22), date(2016, 12, 21)]
>>> differences = [(dates[i]-dates[i-1]).days for i in range(1, len(dates))] #[260, 0, 69, 28, 0, 41, 29]
>>> float(sum(differences))/len(differences)
61.0
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM