'Create a New Column by doing some operations on Existing Column

I am trying to create a column based on the existing column

Distinct Values in both columns will be 1 & 0

New Column Logic:

My New column will be 1 from index where 3 or More than 3 Consecutive 1's will start in Column1 and it will continue till where the index ends with 3 Consecutive 0

Example DataFrame

df = pd.DataFrame([1,1,1,1,1,0,1,1,1,1,0,1,0,0,0,0,0,0,0,1,0,1,0,1,1,
    1,0,1,0,1,0,0,1,0,0,0,0,0,1,1], columns = ['Col1'])

Expected Result

Col1 New_column
1 1
1 1
1 1
1 1
1 1
0 1
1 1
1 1
1 1
1 1
0 1
1 1
0 1
0 1
0 1
0 0
0 0
0 0
0 0
1 0
0 0
1 0
0 0
1 1
1 1
1 1
0 1
1 1
0 1
1 1
0 1
0 1
1 1
0 1
0 1
0 1
0 0
0 0
1 0
1 0


Solution 1:[1]

Use:

df = pd.DataFrame([1,1,1,1,1,0,1,1,1,1,0,1,0,0,0,0,0,0,0,1,0,1,0,1,1,1,0,1,0,1,0,0,1,0,0,0,0,0,1,1, ], columns = ['Col1'])
output = []
state = df.iloc[0].values[0]

for i, row in df.iterrows():
    
    if i>len(df)-3:
            ip1=ip2=0
    else:
        ip1 = df['Col1'][i+1]
        ip2 = df['Col1'][i+2]

    if i-3<0:
        sp1=sp2=1
    else:
        sp1 = df['Col1'][i-1]
        sp2 = df['Col1'][i-2]
        sp3 = df['Col1'][i-3]
    
    if state == 1:
            
        if sp1 == 0 and  sp2== 0 and sp3 == 0:
            output.append(0)
            state = 0
            
        else:
            output.append(1)
    else:
        print(i, state, df['Col1'][i], ip1, ip2)
        if df['Col1'][i] == 1 and ip1 == 1 and ip2 == 1:
            output.append(1)
            state = 1
        else:
            output.append(0)
            
df['res'] = output

output:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1