0

I've list of timestamp values stored in a nested list below.

[[1462692695.0, 1462857370.0, 1463297496.0], 

[1466695088.0, 1466933174.0, 1467067583.0, 1467252502.0, 1467253381.0],

[1455009108.0, 1455218354.0, 1455221295.0], 

[1456098479.0, 1456242604.0, 1456277812.0, 1456683177.0]]

And I want to find the difference between second and first, third and second and so on.. for each of the nested list values.

For example: The newly created difference list:

[[164675,440126],
 [...,...,...,...],
....]
Ch3steR
  • 20,090
  • 4
  • 28
  • 58

3 Answers3

0

You can try this.

for lst in time_stamp_list:
    for x,y in zip(lst[1:],lst):
        print(x-y)

The above can be written as list comprehension.

[[x-y for x,y in zip(lst[1:],lst) ] for lst in time_stamp_list]
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
0

Since you tagged dataframe, here's a pandas solution:

x = [[1462692695.0, 1462857370.0, 1463297496.0], [1466695088.0, 1466933174.0, 1467067583.0, 1467252502.0, 1467253381.0], [1455009108.0, 1455218354.0, 1455221295.0], [1456098479.0, 1456242604.0, 1456277812.0, 1456683177.0]]

df = pd.DataFrame(x)

print (df.diff(axis=1).stack().groupby(level=0).apply(list).tolist())

Or use nested list comprehension:

print ([[b-a for a,b in zip(i, i[1:])] for i in x])

Result:

[[164675.0, 440126.0], [238086.0, 134409.0, 184919.0, 879.0], [209246.0, 2941.0], [144125.0, 35208.0, 405365.0]]
Henry Yik
  • 22,275
  • 4
  • 18
  • 40
  • Thanks a lot. It worked, Also if I want to find the difference between the last and first timestamp. What changes should be made? – Akshay Sachdeva Feb 18 '20 at 10:12
  • For each group you want the difference between first and last, so one value per group? If so use `[i[-1]-i[0] for i in x]`. – Henry Yik Feb 18 '20 at 10:14
0

This answer might be helpful (using only built-in python functions):

x = [[1462692695.0, 1462857370.0, 1463297496.0], [1466695088.0, 1466933174.0, 1467067583.0, 1467252502.0, 1467253381.0], [1455009108.0, 1455218354.0, 1455221295.0], [1456098479.0, 1456242604.0, 1456277812.0, 1456683177.0]]
[[t - s for s, t in zip(a, a[1:])] for a in x]

Result:

[[164675.0, 440126.0],
[238086.0, 134409.0, 184919.0, 879.0],
[209246.0, 2941.0],
[144125.0, 35208.0, 405365.0]]
Gillu13
  • 898
  • 6
  • 11