Reputation: 2297
My dataframe looks like this:
time mid price dse_high_born
18 2019-04-22 00:05:15 0.001854 False
19 2019-04-22 00:05:30 0.001854 False
20 2019-04-22 00:05:45 0.001854 False
21 2019-04-22 00:06:00 0.001854 False
22 2019-04-22 00:06:15 0.001854 True
23 2019-04-22 00:06:30 0.001854 True
24 2019-04-22 00:06:45 0.001854 True
25 2019-04-22 00:07:00 0.001856 True
26 2019-04-22 00:07:15 0.001856 True
27 2019-04-22 00:07:30 0.001856 True
28 2019-04-22 00:07:45 0.001856 True
29 2019-04-22 00:08:00 0.001856 False
30 2019-04-22 00:08:15 0.001856 False
So basically what I need is to iterate through the column dse_high_born
when the column turns to True
, select at the same row the value Time
and mid price
from the two other columns and add them into a new column Time1
and Price1
at the same index.
After that, when the column dse_high_born
turns to False
select the same two values (time, mid price) on the same row and add them at the same index in two new column Time2
and Price2
.
I tried to iterate and use the function continue
but it did not work at all... I am a bit stuck! Any idea? Thanks in advance!
The results that I need would be something like that:
time mid price dse_high_born Time1 price1 Time2 Price2
2019-04-22 00:05:15 0.001854 False
2019-04-22 00:05:30 0.001854 False
2019-04-22 00:05:45 0.001854 False
2019-04-22 00:06:00 0.001854 False
2019-04-22 00:06:15 0.001854 True 2019-04-22 00:06:15 0.001854
2019-04-22 00:06:30 0.001854 True
2019-04-22 00:06:45 0.001854 True
2019-04-22 00:07:00 0.001856 True
2019-04-22 00:07:15 0.001856 True
2019-04-22 00:07:30 0.001856 True
2019-04-22 00:07:45 0.001856 True 2019-04-22 00:07:45 0.001856
2019-04-22 00:08:00 0.001856 False
2019-04-22 00:08:15 0.001856 False
Upvotes: 0
Views: 39
Reputation: 150785
To detect value changes, use shift()
:
changes = df['dse_high_born'].ne(df['dse_high_born'].shift()
and then:
changes_at_true = changes & df['dse_high_born']
changes_at_false = changes & ~df['dse_high_born']
gives changes occurs at True
values. So you can do:
df.loc[changes_at_true, ['Time', 'mid_price']] += df.loc[changes_at_true, ['Time1', 'Price1']]
Edit: if you want to copy the values into new columns, do:
df['Time1'] = ''
df['Price1'] = ''
df.loc[changes_at_true, ['Time1', 'Price1']] = df.loc[changes_at_true, ['Time', 'mid_price']]
Upvotes: 1