1

I Want to calculate the ID time difference ,For example ID 0 TimeStamp 1176 - ID 0 TimeStamp 1163 = 13 ,ID 0 TimeStamp 1190 - ID 0 TimeStamp 1176 = 14 ,How to do it ?

expected

     TimeStamp  Input ID   diff   
0         1163  T      0    NaN 
1         1163  T      1    NaN  
2         1163  T      2    NaN   
3         1163  T      3    NaN    
4         1176  T      0     13  
5         1176  T      1     13  
6         1176  T      2     13  
7         1176  T      3     13  
8         1190  T      0     14
9         1190  T      1     14 
10        1190  T      2     14 
CHL
  • 57
  • 7

1 Answers1

1

Assuming your dataframe looks like

    TimeStamp Input  ID
0        1163     T   0
1        1163     T   1
2        1163     T   2
3        1163     T   3
4        1176     T   0
5        1176     T   1
6        1176     T   2
7        1176     T   3
8        1190     T   0
9        1190     T   1
10       1190     T   2

You can groupby the ID and use pd.diff() on each group and add that back into the results.

df["diff"] = df.groupby("ID")["TimeStamp"].diff()

    TimeStamp Input  ID  diff
0        1163     T   0   NaN
1        1163     T   1   NaN
2        1163     T   2   NaN
3        1163     T   3   NaN
4        1176     T   0  13.0
5        1176     T   1  13.0
6        1176     T   2  13.0
7        1176     T   3  13.0
8        1190     T   0  14.0
9        1190     T   1  14.0
10       1190     T   2  14.0

Note: the sort order of the dataframe is important. It must be sorted by TimeStamp in ascending order. If you need to do that, you can first use df.sort_values("TimeStamp", inplace=True).

rchome
  • 2,623
  • 8
  • 21