Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending array by repeating values if another array is not continues

I am tracking some particles on a flat surface using the TrackPy plugin. This results in a dataframe with positions in x and y and a corresponding frame number, here illustrated by a simple list:

x=[80.1,80.2,80.1,80.2,80.3]
y=[40.1,40.2,40.1,40.2,40.3]
frame = [1,2,3,4,5]

However, due to the experimental setup, one may lose the particle for a single frame resulting in:

x=[80.1,80.2,80.1,80.2,80.3]
y=[40.1,40.2,40.1,40.2,40.3]
frame = [1,2,3,4,6]

Now i would like to extend all list, so that ´frame´ is continues and 'x,y' will repeat the previous value if no frame is present in the original data resulting in something like:

x=[80.1,80.2,80.1,80.2,80,2,80.3]
y=[40.1,40.2,40.1,40.2,40.2,40.3]
frame = [1,2,3,4,5,6]
like image 226
S. Nielsen Avatar asked Jan 28 '23 12:01

S. Nielsen


1 Answers

You can use Pandas, which internally utilizes NumPy arrays:

import pandas as pd

df = pd.DataFrame({'x': x, 'y': y}, index=frame)

df = df.reindex(np.arange(df.index.min(), df.index.max()+1)).ffill()

Result

print(df)

      x     y
1  80.1  40.1
2  80.2  40.2
3  80.1  40.1
4  80.2  40.2
5  80.2  40.2
6  80.3  40.3

You can then extract your result to lists:

x = df['x'].tolist()
y = df['y'].tolist()
frame = df.index.tolist()
like image 132
jpp Avatar answered Jan 30 '23 03:01

jpp