如何基于另一个变量中的连续值将函数应用于变量

时间:2019-04-11 17:48:06

标签: python dataframe variables iteration

我有一个数据帧,其中的图像编号(sliceno)以及x和y坐标(分别为x位置和y位置)。这些图像是随时间拍摄的,相同的切片编号表示在同一时间点记录的多个坐标。

我想比较图像的坐标与之前的坐标。如果后续图像的x坐标为+/- 1或等于先前图像的x坐标,并且发生两次,即存在两个切片的两个记录都满足坐标要求。 y坐标也一样。

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

1 个答案:

答案 0 :(得分:1)

我试图将其分解以清楚说明正在发生的事情,但这应该为您提供两个新列“ x”和“ y”,其中包含一个布尔值,用于确定是否满足您的条件。

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',))

您绝对可以将其压缩一堆,但这是一个很好的起点。

相关问题