首页 > 解决方案 > pandas drop rows after value appears

问题描述

I have a dataframe:

df = pd.DataFrame({'Position': [1,2,3,4,5,'Title','Name','copy','Thanks'], 'Winner': [0,0,0,0,0,'Johnson',0,0,0]})

I want to drop all the rows after and including the row Johnson appears in. This would give me a dataframe looking like:

df = pd.DataFrame({'Position': [1,2,3,4,5], 'Winner': [0,0,0,0,0]})

I have tried referencing the index that 'Johnson' appears in the slicing the dataframe using the index. But this didn't work for.

thanks

标签: pythonpandas

解决方案


你只需要布尔索引和cumsum

df[df.Winner.eq('Johnson').cumsum().lt(1)]

输出:

  Position Winner
0        1      0
1        2      0
2        3      0
3        4      0
4        5      0

推荐阅读