Reputation: 3409
i have the following dataframe , need to add a third boolean column with 0 or 1 value, the value of the column would be 1 if the price
column for both two previous day is 0.12 otherwise it would be 0
date price new_column
'2017-10-11' 0.13 0
'2017-10-12' 0.12 0
'2017-10-13' 0.12 0
'2017-10-14' 0.15 1
'2017-10-15' 0.13 0
'2017-10-16' 0.12 0
'2017-10-17' 0.12 0
'2017-10-18' 0.15 1
one solution can be first adding two columns that keep yesterday price and the day before yesterday price then when these two columns are both 0.12 new_column
would be 1 but i am looking for a more efficient and faster solution without need to add too much extra columns
Upvotes: 2
Views: 48
Reputation: 862611
Compare shift
ed columns and cast boolean mask
to int
:
df['new'] = ((df['price'].shift(1) == 0.12) & (df['price'].shift(2) == 0.12)).astype(int)
print (df)
date price new_column new
0 '2017-10-11' 0.13 0 0
1 '2017-10-12' 0.12 0 0
2 '2017-10-13' 0.12 0 0
3 '2017-10-14' 0.15 1 1
4 '2017-10-15' 0.13 0 0
5 '2017-10-16' 0.12 0 0
6 '2017-10-17' 0.12 0 0
7 '2017-10-18' 0.15 1 1
Upvotes: 2