简体   繁体   中英

Pandas dataframe if 3 consecutive numbers

I have a dataframe df

    Price
0    3
1    3
2    3
3    -3
4    3
5    3

I wanted to make a column which says TRUE if there are 2 positive numbers in a row

So the output is

    Price    output
0    3        FALSE
1    3        TRUE
2    3        TRUE
3    -3       FALSE
4    3        FALSE
5    3        TRUE

Use .shift(1) to look at the value in the previous row:

df['two_positive'] = (df['Price'] >= 0) & (df['Price'].shift(1) >= 0)

Result:

    Price   two_positive
0   3       False
1   3       True
2   3       True
3   -3      False
4   3       False
5   3       True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM