Syntax to select previous row in pandas after filtering
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop
--
Chapters
00:00 Question
00:56 Accepted answer (Score 15)
01:25 Answer 2 (Score 4)
01:42 Answer 3 (Score 2)
01:55 Answer 4 (Score 2)
02:07 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
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop
--
Chapters
00:00 Question
00:56 Accepted answer (Score 15)
01:25 Answer 2 (Score 4)
01:42 Answer 3 (Score 2)
01:55 Answer 4 (Score 2)
02:07 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