如何仅选择 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
我可以用一些丑陋的代码如果只有一个 id 来做到这一点,但我不知道如何将类似的逻辑应用于所有组:
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]
请您参考如下方法:
一个选项是使用 groupby 和 cumprod。
df[df.val.gt(5)[::-1].groupby(df.id).cumprod().reindex_like(df)]
如果您不介意 UserWarning,您可以进一步缩短它:
df[df[df.val.gt(5)[::-1].groupby(df.id).cumprod()]
id val
3 1 10
4 1 20
5 1 30
9 2 12
10 2 17
11 2 28
