I want to calculate the difference with conditions, how to do it?
Source date
TimeStamp Input match
1 38563 Touch False
2 38568 Pen False
3 38577 Touch False
4 38580 Pen False
5 38589 Pen True
6 38591 Touch False
expect result
TimeStamp Input match diff
1 38563 Touch False NaN
2 38568 Pen False NaN
3 38577 Touch False NaN
4 38580 Pen False NaN
5 38589 Pen True 1
6 38591 Touch False NaN
CodePudding user response:
Create groups by consecutive True
s and pass to DataFrameGroupBy.diff
:
df['diff'] = df.groupby((~df['match']).cumsum()[df['match']])['TimeStamp'].diff()
print (df)
TimeStamp match diff
0 38269 False NaN
1 38340 True NaN
2 38341 True 1.0
3 38349 True 8.0
4 38350 True 1.0
5 38351 False NaN
6 38358 False NaN
7 38358 True NaN
8 38366 False NaN
9 38370 False NaN