Syntax to select previous row in pandas after filtering
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5
--
Chapters
00:00 Syntax To Select Previous Row In Pandas After Filtering
00:43 Accepted Answer Score 15
01:05 Answer 2 Score 4
01:18 Answer 3 Score 2
01:28 Answer 4 Score 2
01:36 Thank you
--
Full question
https://stackoverflow.com/questions/5103...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #dataframe #conditionalstatements
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5
--
Chapters
00:00 Syntax To Select Previous Row In Pandas After Filtering
00:43 Accepted Answer Score 15
01:05 Answer 2 Score 4
01:18 Answer 3 Score 2
01:28 Answer 4 Score 2
01:36 Thank you
--
Full question
https://stackoverflow.com/questions/5103...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #dataframe #conditionalstatements
#avk47
ACCEPTED ANSWER
Score 15
Shift the mask up by 1.
df[(df['Value'] < 15).shift(-1).fillna(False)]
Row Value
1 2 25
More generally, if you're trying to find all rows greater than 15, whose next row is lesser than 15, you can compute two separate masks and AND them:
df[(df['Value'].shift(-1) < 15) & (df['Value'] > 15)]
Row Value
1 2 25
ANSWER 2
Score 4
np.flatnonzero
To find where the mask is True then subtract one
df.iloc[np.flatnonzero(df.Value < 15) - 1]
Row Value
1 2 25
ANSWER 3
Score 2
Using idxmax
>>> df.iloc[df.Value.le(15).idxmax() - 1]
Row 2
Value 25
ANSWER 4
Score 2
Using nonzero
df.iloc[(df['Value'] < 15).nonzero()[0]-1]
Out[34]:
Row Value
1 2 25