Python 从熊猫组中找出平均日间隔

Python 从熊猫组中找出平均日间隔,python,pandas,Python,Pandas,我使用的是python 3,其数据帧如下所示: df = pd.DataFrame({'product':['P01','P01','P01','P02'],'date':['2017-01-01','2017-01-15','2017-01-20','2017-01-01']}) 我的数据是这样的 product date P01 2017-01-01 P01 2017-01-15 P01 2017-01-20 P02

我使用的是python 3,其数据帧如下所示:

df = pd.DataFrame({'product':['P01','P01','P01','P02'],'date':['2017-01-01','2017-01-15','2017-01-20','2017-01-01']})
我的数据是这样的

product      date
P01          2017-01-01
P01          2017-01-15
P01          2017-01-20
P02          2017-01-01
我想按产品找出平均日间隔组,预期结果如下

product       daygap (avg)
P01        (14 + 5)/2 = 9.5  -> 14 is the difference between 2017-01-15 and 2017-01-01
                             -> 5 is the difference between 2017-01-20 and 2017-01-15
P02             0 -> There is no day gap

你能给我一些建议吗?提前感谢。

您可以在按产品对数据框进行分组后,将
diff
mean
on-date列一起使用:

df.date = pd.to_datetime(df.date)
df.groupby('product').date.agg(lambda x: x.diff().mean()).dt.total_seconds()/(24*3600)

#   product
#P01    9.5
#P02    NaN
#Name: date, dtype: float64