I have a dataframe with:
column 1 : a list of particles
column 2: the frame in which they are observed in a video
column 3: measurement x
I need to compare the particles’ measurements over the time they are visible in the video. I cannot use the frame directly, since I need it to be relative to the first time each particle appears in the video. Some frames contain more than one particle.
I am thinking I need to create a column for the relative frame, find the different particles and fill that column with the relative frame.
I can do it step by step for one particle with:
df2=df.query('particle=={x}')
and then
df2['relativeframe']=(df2.frame-df3.index[0])
However I am a beginner at Python (and at coding in general), so I can’t figure out how to scale that to all the particles in all the video.
Can you please let me know how you would approach this problem? Thank you!
Advertisement
Answer
Try this:
# For each particle, find the first time it appears in a video frame first = df.groupby('particle')['frame'].min().rename('first_frame') # Combine it with the original DataFrame result = df.merge(first, left_on='particle', right_index=True) # Find the relative frame result['relative_frame'] = result['frame'] - result['first_frame']