\$\begingroup\$
\$\endgroup\$
0
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?
1 Answer 1
\$\begingroup\$
\$\endgroup\$
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 "invert" the 0's and 1's
df = 1 - a.cummax().shift(fill_value=0) # [1,1,1,0,0,0]
answered Feb 1, 2021 at 17:51
default