我如何找到一个会话(针对每个组)的第一个元素,该元素开始一系列新的连续值?
import pandas as pd
df = pd.DataFrame({'group':[1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,], 'value':[
1,2,3,4,5,10,11, 15, 16,17,18,19,20, # 13
21, 22,23,24,26,27.28,
4,5,6, 8,9,10,11,12, 13,14
]})
display(df)
到目前为止,我被困在这里:
df['shifted_value'] = df['value'].shift(-1)
df['difference_nect'] = df['shifted_value'] - df['value']
# this is obviously not yet correct - how can I get the first element (elemnt of 0 for each of the starting sessions)
df['session_element_index'] = df.groupby(['group']).cumcount()
df.head()
在SQL中,我会使用窗口函数并比较前一个/下一个元素,以确定会话是否开始/结束。有没有更好的熊猫原生方式——如何以矢量化的方式做到这一点?