1
\$\begingroup\$

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?

\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

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]
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.