假設我有這個資料框:
df = {'ID' : [1, 1, 1, 1, 1, 1, 1, 2, 2],
'x':[76.551, 79.529, 78.336,77, 76.02, 79.23, 77.733, 79.249, 76.077],
'y': [151.933, 152.945, 153.970, 119.369, 120.615, 118.935, 119.115, 152.004, 153.027],
'position': ['start', 'end', 'start', 'NA', 'NA','NA','end', 'start', 'end']}
df = pd.DataFrame(df)
df
ID x y position
0 1 76.551 151.933 start
1 1 79.529 152.945 end
2 1 78.336 153.970 start
3 1 77.000 119.369 NA
4 1 76.020 120.615 NA
5 1 79.230 118.935 NA
6 1 77.733 119.115 end
7 2 79.249 152.004 start
8 2 76.077 153.027 end
我想洗掉與某些值之間的端點關聯的所有行。我可以指定要洗掉的端點:
df[(df['position'] == 'end') & (df['x'] > 75) & (df['x'] < 78)]
但是如何洗掉與該條件關聯的所有行?
輸出看起來像:
ID x y position
0 1 76.551 151.933 start
1 1 79.529 152.945 end
編輯:背景關系是這些是來自不同動物的軌跡(具有特定 ID),如果動物的末端坐標位于特定的 x 軸值之間,我想從模型中洗掉該動物的整個軌跡。
uj5u.com熱心網友回復:
試試這個,使用DataFrame.drop:
rows_to_remove = df[(df['position'] == 'end') & (df['x'] > 75) & (df['x'] < 78)].index.values
df = df.drop(rows_to_remove)
uj5u.com熱心網友回復:
您可以使用布爾掩碼:
m = (df['position'] == 'end') & (df['x'] > 75) & (df['x'] < 78)
out = df[~m.groupby(df['position'].eq('start').cumsum()).transform('max')]
print(out)
# Output
ID x y position
0 1 76.551 151.933 start
1 1 79.529 152.945 end
我已經在您之前的問題df['position'].eq('start').cumsum()中使用過創建虛擬組來識別不同的軌跡。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/450698.html
