I would like to select data in df2 based on time intervals in df1:
df1:
ID Start End col1 col2
23468 2011-01-03 01:01:03 2011-01-03 01:04:05 10 a
23468 2011-01-15 08:20:00 2011-01-18 01:01:01 50 b
23468 2011-02-03 01:07:20 2011-02-08 12:00:03 150 a
33525 2011-02-03 01:07:19 2011-02-06 12:00:03 10 a
...
df2:
ID Timestap col3 col4
23468 2011-01-03 01:01:03 3 aa
23468 2011-01-03 01:02:00 4 bb
23468 2011-01-03 12:01:03 7 aa
33525 2011-02-03 02:31:03 10 aa
33525 2011-02-04 12:01:03 20 aa
33525 2011-02-05 14:00:01 30 aa
...
I need to filter df2 if ID matches that in df1 and Timestamp is in between Start and End in df1, then calculate the average of col3 of the group and create a new column in df1 called Average, expected output:
ID Start End col1 col2 Average
23468 2011-01-03 01:01:03 2011-01-03 01:04:05 10 a 3.5
23468 2011-01-15 08:20:00 2011-01-18 01:01:01 50 b nan
23468 2011-02-03 01:07:20 2011-02-08 12:00:03 150 a nan
...
33525 2011-02-03 01:07:19 2011-02-06 12:00:03 10 a 20
...
I tried using a for-loop but it takes ages as the dataframes are too large and merging two dataframes will take even longer, I am wondering if apply() with lambda expression can solve this issue? How do I refer to time intervals from another df?
Update:
What if I want to filter df2 based on time intervals in df1, then find the difference between the first and last col3(ie. 6-3 =3), divide this value by the difference between the first and last Timestamp(ie. 2011-01-03 01:03:03 - 2011-01-03 01:01:03 = 120 seconds). So expected value is 3/120=0.025.
df1:
ID Start End col1 col2
23468 2011-01-03 01:01:03 2011-01-03 01:04:05 10 a (*)
23468 2011-01-15 08:20:00 2011-01-18 01:01:01 50 b
23468 2011-02-03 01:07:20 2011-02-08 12:00:03 150 a
33525 2011-02-03 01:07:19 2011-02-06 12:00:03 10 a
...
df2:
ID Timestap col3 col4
23468 2011-01-03 01:01:03 3 aa first row in time interval (*)
23468 2011-01-03 01:02:00 4 bb
23468 2011-01-03 01:03:03 6 aa last row in time interval (*)
23468 2011-01-03 12:01:03 7 aa
33525 2011-02-03 02:31:03 10 aa
33525 2011-02-04 12:01:03 20 aa
33525 2011-02-05 14:00:01 30 aa
So the expected output:
ID Start End col1 col2 Average
23468 2011-01-03 01:01:03 2011-01-03 01:04:05 10 a 0.025 (3/120=0.025)
23468 2011-01-15 08:20:00 2011-01-18 01:01:01 50 b nan
23468 2011-02-03 01:07:20 2011-02-08 12:00:03 150 a nan
...
33525 2011-02-03 01:07:19 2011-02-06 12:00:03 10 a 0.000067032 (20/298364 =0.000067032)
...