Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

python 3.x - Pandas transform series values until condition is met without for loop

I asked this question on Code Review first, but didn't get any response so I am posting it here.

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?

question from:https://stackoverflow.com/questions/65952814/pandas-transform-series-values-until-condition-is-met-without-for-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can shift values by Series.shift with cumulative sum and compare 0 and pass to numpy.where:

print (np.where(df.shift(fill_value=0).cumsum().eq(0), 1, 0))
[1 1 1 0 0 0]

Or convert mask to integers:

print (df.shift(fill_value=0).cumsum().eq(0).astype(int))
0    1
1    1
2    1
3    0
4    0
5    0
dtype: int32

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...