I am basically trying to loop through a dataframe that has been grouped and finding the index that has the nearest value to the input argument.
For example, given the dataframe below, for every group defined by the global_id, I want to group to take frames that are spaced at least 10 frames apart. For example if I have a list of frames [1,2,3,4,14,20,30,31], the output would be [1,14,30] because
- I would initialize by taking frame 1 as the first frame
- The next frame that is at least 10 frames apart would be frame number 14
- The following frame that is at least 10 frame apart from 14 is 30
As such, the resulting before and after dataframe should look like below
Before
seq_name label pedestrian_id frame_no global_id
0 0001 crossing 0001 0001 1
1 0001 crossing 0001 0002 1
2 0001 crossing 0001 0003 1
3 0001 crossing 0001 0004 1
4 0001 crossing 0001 0005 1
5 0001 crossing 0001 0006 1
6 0001 crossing 0001 0007 1
7 0001 crossing 0001 0008 1
8 0001 crossing 0001 0009 1
9 0001 crossing 0001 0010 1
10 0001 crossing 0002 0001 2
11 0001 crossing 0002 0012 2
12 0001 crossing 0002 0013 2
13 0001 crossing 0002 0014 2
14 0001 crossing 0002 0015 2
15 0001 crossing 0002 0029 2
16 0001 crossing 0002 0030 2
17 0001 crossing 0002 0031 2
18 0001 crossing 0002 0032 2
19 0001 crossing 0002 0033 2
20 0002 crossing 0001 0034 3
21 0002 crossing 0001 0035 3
22 0002 crossing 0001 0036 3
23 0002 crossing 0001 0037 3
24 0002 crossing 0001 0038 3
25 0002 crossing 0001 0039 3
26 0002 crossing 0001 0049 3
27 0002 crossing 0001 0050 3
28 0002 crossing 0001 0051 3
29 0002 crossing 0001 0052 3
After filter
seq_name label pedestrian_id frame_no global_id
0 0001 crossing 0001 0001 1
10 0001 crossing 0002 0001 2
11 0001 crossing 0002 0012 2
15 0001 crossing 0002 0029 2
25 0002 crossing 0001 0039 3
26 0002 crossing 0001 0049 3
Below is what I have. Once I have the indices I can create a new dataframe by indexing from the old. I am still new to Pandas and it looks extremely cumbersome so I am hoping there is a more elegant solution. I have read through the docs on groupby and some other SO posts but still cant figure it out. This isn't a homework. Just trying to clean up my data processing pipeline by replacing everything with Pandas.
ind = []
for j in df["global_id"].unique():
df_temp = df[df["global_id"] == j][["frame_no"]]
df_temp["frame_no"] = pd.to_numeric(df["frame_no"])
start_frame = df_temp["frame_no"].min()
end_frame = df_temp["frame_no"].max()
i = start_frame-1
while i < end_frame:
ind.append(np.min(df_temp[(df_temp["frame_no"] > i) & (df_temp["frame_no"] < i+10)].index.tolist()))
i+=10