Python - save x values from a column to list when a number in another column is bigger than the number before 2

Viewed 94

(Hi I'm new to this so I might not know the best way to formulate this question but here goes)

I'm using pandas btw!

I am looking for a construct to each time save x values (let's say x=3 so three values) from one column to a list when a number in another column is bigger than the number before. First number should not be considered. Important to note that there are also missing data in the number column (NaN).

Number         Value
23             4
23             5
NaN            8
24             6    # <--
24             23
24             26
24             11
25             2    # <--
25             1
25             3
25             5
Nan            9
26             4    # <--
26             6
NaN            9
26             12

Hopefully in the end the new list contains:

List = [6, 2, 4]

Thanks for helping me out !

2 Answers

IIUC, try with ffill and then compare if series.diff() is greater then 0, then slice the number of elements you want in x(here 3):

x=3
df.loc[df['NumberColumn'].ffill().diff().gt(0),'Value'].tolist()[:x]
#[6, 2, 4]

You can run:

df.Value[df.Number.shift().ffill() < df.Number].tolist()[:3]

(replace 3 with your number of choice).

Related