Pandas transform series values until condition is met without for loop I have a pandas Series contain 0s and 1s. Now I want to convert all the 0s to 1s which come before the first 1, and rest of the 1s to 0s. I can achieve that using the below code:
import pandas as pd
a = [0,0,1,0,0,1]
df = pd.Series(a)
flag = True
for i in range(df.shape[0]):
  if (df[i]!=1) &amp; flag:
    df[i]=1
  elif flag:
    flag=False
  else:
    df[i]=0
print(df)

Final dataframe:
[1,1,1,0,0,0]

But how can I optimize it? Perhaps by avoiding the for loop?
Use a combination of Series.cummax() and Series.shift()
a = pd.Series([0,0,1,0,0,1])

a.cummax()                               # [0,0,1,1,1,1]

a.cummax().shift(fill_value=0)           # [0,0,0,1,1,1]

Then &quot;invert&quot; the 0's and 1's
df = 1 - a.cummax().shift(fill_value=0)  # [1,1,1,0,0,0]