2017-01-12 48 views
2

我有數據幀熊貓:日期之間的計數值差值

ID date 
111 11-11-2016 
111 14-11-2016 
111 17-11-2016 
222 24-11-2016 
222 27-11-2016 

我需要統計數據之間的差異,以每一個ID。 我使用

df['duration'] = df.groupby(['ID','date']).date.apply(lambda x: x - x.iloc[0]) 
idx = df.groupby(['ID'])['duration'].transform(max) == df['count date'] 

但它返回錯誤的結果。 我如何獲得理想? 我需要

ID count date 
111 6 
222 3 

回答

4
>>> df.groupby('ID')['date'].apply(lambda x: x.max() - x.min()) 
ID 
111 6 days 
222 3 days 

也有可能與numpy.ptp

>>> df.groupby('ID')['date'].agg(np.ptp) 
ID 
111 6 days 
222 3 days 
1

使用內置minagg的和max
See this post

d1 = df.groupby('ID').date.agg(['min', 'max']).diff(axis=1)['max'] 

ID 
111 6 days 
222 3 days 
dtype: timedelta64[ns]