我跟踪了大量事件,并在每个事件后附加了时间戳:
我目前有下表:
ID Time_Stamp Event
1 2/20/2019 18:21 0
1 2/20/2019 19:46 0
1 2/21/2019 18:35 0
1 2/22/2019 11:39 1
1 2/22/2019 16:46 0
1 2/23/2019 7:40 0
2 6/5/2019 0:10 0
3 7/31/2019 10:18 0
3 8/23/2019 16:33 0
4 6/26/2019 20:49 0
我想要的是以下内容[但不确定是否可行]:
ID Time_Stamp Conversion Total_Duration_Days Conversion_Duration
1 2/20/2019 18:21 0 2.555 1.721
1 2/20/2019 19:46 0 2.555 1.721
1 2/21/2019 18:35 0 2.555 1.721
1 2/22/2019 11:39 1 2.555 1.721
1 2/22/2019 16:46 1 2.555 1.934
1 2/23/2019 7:40 0 2.555 1.934
2 6/5/2019 0:10 0 1.00 0.000
3 7/31/2019 10:18 0 23.260 0.000
3 8/23/2019 16:33 0 23.260 0.000
4 6/26/2019 20:49 0 1.00 0.000
总持续时间#1 = Max Date - Min Date
[2.555天]
对于#2转换持续时间 = Conversion Date - Min Date
[1.721天]-发布以下操作后,转换可以保持在计算出的持续时间
我尝试了以下操作:
df.reset_index(inplace=True)
df.groupby(['ID'])['Time_Stamp].diff().fillna(0)
我想要的是这种方法,但是它显示的是每个事件之间的差异,而不是最小时间戳与最大时间戳的区别
conv_test = df.reset_index(inplace=True)
min_df = conv_test.groupby(['ID'])['visitStartTime_aest'].agg('min').to_frame('MinTime')
max_df = conv_test.groupby(['ID'])['visitStartTime_aest'].agg('max').to_frame('MaxTime')
conv_test = conv_test.set_index('ID').merge(min_df, left_index=True, right_index=True)
conv_test = conv_test.merge(max_df, left_index=True, right_index=True)
conv_test['Durartion'] = conv_test['MaxTime'] - conv_test['MinTime']
这给了我Total_Duration_Days
,这很不错[随时提供更优雅的解决方案
关于如何获得Conversion_Duration
的任何想法?
答案 0 :(得分:1)
您可以将GroupBy.transform
与min
一起使用,将max
与Series
一起使用,其大小与原始大小相同,因此可以减去Total_Duration_Days
,然后仅过滤{{按1
行1}}行,按DataFrame.set_index
行创建Event
并转换为Series
,然后转换为Series.map
以得到新的Series,因此可以每组减去最小值:
dict
由于仅为该组添加了每个组可能有多个df['Time_Stamp'] = pd.to_datetime(df['Time_Stamp'])
min1 = df.groupby('ID')['Time_Stamp'].transform('min')
max1 = df.groupby('ID')['Time_Stamp'].transform('max')
df['Total_Duration_Days'] = max1.sub(min1).dt.total_seconds() / (3600 * 24)
d = df.loc[df['Event'] == 1].set_index('ID')['Time_Stamp'].to_dict()
new1 = df['ID'].map(d)
的解决方案-测试,如果掩码中每个组有更多1
,请获得系列1
,然后使用Series.combine_first
与new2
系列mapped
一起使用。
原因是提高性能,因为处理多个1有点复杂。
new1