Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply function on variable based on consecutive values in another variable

I have a data frame with the image number (sliceno) and x and y coordinates (x-position and y-position, respectively). These images are taken over time and the same slice number indicates multiple coordinates recorded at the same timepoint.

I want to compare coordinates of images to the one(s) before. If the x coordinate of a subsequent image is +/-1 or equal to x coordinate of the previous image and this happens twice, i.e. there are two recordings of the same sliceno which satisfy the coordinate requirements. The same for the y coordinates.

import pandas as pd

print(dataframe)
x-position  y-position  radius (pixels)  r-squared of radius fitting sliceno
0          220         220           19.975                        0.987       6
1          627         220           20.062                        0.981       6
2          620         220           20.060                        0.981       6
3          220         220           19.975                        0.987       7
4          628         220           20.055                        0.980       7
like image 831
sforbes Avatar asked Nov 07 '22 18:11

sforbes


1 Answers

I tried to break this down to make it clear what is going on, but this should give you two new columns 'x' and 'y' that contain a boolean for whether or not your criteria was met.

import pandas as pd

df = pd.DataFrame(
    columns=['x-position', 'y-position', 'radius', 'r-squared', 'sliceno'],
    index=[i for i in range(5)],
    data=[
        [220, 220, 19.975, 0.987, 6],
        [627, 220, 20.062, 0.981, 6],
        [620, 220, 20.060, 0.981, 6],
        [220, 220, 19.975, 0.987, 7],
        [628, 220, 20.055, 0.980, 7],
    ]
)
df['x_previous'] = df['x-position'].shift()
df['y_previous'] = df['y-position'].shift()
df['slice_previous'] = df['sliceno'].shift()

def check_within_one(row, axis):
    within_1 = (True if row[axis + '_previous'] - 1 <=
                        row[axis + '-position'] <=
                        row[axis + '_previous'] + 1 and
                        row['sliceno'] == row['slice_previous']
                else False)

    return within_1

df['x'] = df.apply(check_within_one, axis=1, args=('x',))
df['y'] = df.apply(check_within_one, axis=1, args=('y',))

You can definitely condense this down a bunch, but it's a good starting point.

like image 97
ATK7474 Avatar answered Nov 14 '22 21:11

ATK7474