获取最后一次在 pandas 中出现特定值之后的所有行 [英] Get all rows after the last occurrence of a specific value in pandas
本文介绍了获取最后一次在 pandas 中出现特定值之后的所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据框看起来像
ID colA
1 B
1 D
2 B
2 D
2 C
我已返回每个组中最后一次发生事件B之后的所有行.输出将是:
I have return all rows after the last occurrence of event B in each group. The output will be :
ID colA
1 D
2 D
2 C
我尝试了
a = df['colA'].str.contains('B').groupby(df['ID'])
b = df[(a.transform('sum') - a.cumsum()).eq(0)]
,到目前为止一切正常.我只是想知道是否有其他替代方法可以实现这一目标?
and it's working fine so far. I am just wondering if there is any alternative approach to achieve this?
推荐答案
反转行(这很重要).然后调用 groupby
和 cumsum
,并获取(求反的)总和值为零的所有行.
Reverse your rows (this is important). Then call groupby
and cumsum
, and take all rows with (reversed) cumsum value equal to zero.
df[df.colA.eq('B')[::-1].astype(int).groupby(df.ID).cumsum().eq(0)]
ID colA
1 1 D
3 2 D
4 2 C
这篇关于获取最后一次在 pandas 中出现特定值之后的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文