Как выбрать только те строки, где val
больше 5 до последней записи в каждом id
этого образца данных?
df = pd.DataFrame({'id': [1,1,1,1,1,1,2,2,2,2,2,2],
'val': [10,1,1,10,20,30,1,1,1,12,17,28]})
id val
1 10 <- meets the condition, but condition fails in the next 2 rows
1 1
1 1
1 10 <- meets the condition until the end of this id
1 20
1 30
2 1
2 1
2 1
2 12
2 17
2 28
Желаемый вывод:
id val
1 10
1 20
1 30
2 12
2 17
2 28
Я могу сделать это с помощью некрасивого кода , если есть только один идентификатор , но я не знаю, как применить подобную логику ко всем группам:
df = pd.DataFrame({'id': [1,1,1,1,1,1],
'val': [10,1,1,10,20,30]})
# create groups at breakpoints where condition is no longer met
g = df.groupby((df['val'] > 5).cumsum())
# find last group
label = max(list(g.groups.keys()))
result = df.loc[g.groups[label]._data]
# result still includes some rows where the condition is not met
result = result[result > 5]