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) & 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?