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?

asked Jan 28, 2021 at 10:00
\$\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]
answered Feb 1, 2021 at 17:51
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.