简体   繁体   中英

Bit wise operator manipulation

I have a column within a dataframe that consists of either 1 , 0 or -1 . For example:

<0,0,0,1,0,0,1,0,0,1,0,-1,0,0,1,0,0,-1,0,0,1,0,0,1,0,0,1,0,0,0,-1,0,0>

How can I create a new column in that dataframe where it is a sequence of 1s from the first 1 to the first -1 . And then starts again at 0 until the next 1 .

In this example, it would be:

<0,0,0,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,0,0,1,1,1,1,0,0,1,1,1,1, 1,0,0>

Essentially I'm trying to create a trading strategy where I buy when the price is >1.25 and sell when goes below 0.5 . 1 represents buy and -1 represents sell. If I can get it into the form above I can easily implement it.

Not sure how your data is stored but an algorithm similar to the following might work without the use of bitwise operators

x = [0,0,0,1,0,0,1,0,0,1,0,-1,0,0,1,0,0,-1,0,0,1,0,0,1,0,0,1,0,0,0,-1,0,0]
newcol = []
flag = 0
for char in x:
    if char == 1 and flag == 0:
        flag = 1

    newcol.append(flag)

    if char == -1 and flag == 1:
        flag = 0

print(newcol)

Seems like a good use case for :

import pandas as pd


s = pd.Series([0,0,0,1,0,0,1,0,0,1,0,-1,0,0,1,0,0,-1,0,0,1,0,0,1,0,0,1,0,0,0,-1,0,0])
s2 = s.groupby(s[::-1].eq(-1).cumsum()).cummax()

print(s2.to_list())

Output:

[0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]

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