<p>我自己解决了一个丑陋的方式,见下文。不过,我还是想知道有没有更好的方法来做这件事。在</p>
<pre><code>test_series = pd.Series(data = [0,2,0,2,3,6,3,0])
bool_df = pd.DataFrame(data= [(test_series>1), (test_series>5)]).T
bool_df.loc[:,0] = (bool_df.loc[:,0])&(~bool_df.loc[:,1])
# make a boolean DataFrame.
# Column 0 is values between 1 and 5, and column 1 is values above 5.
# the resulting boolean series we are looking for is column 1 after it has been modified in the following way.
k=0 # k is an integer that indexes the bool_df values that are less than 1
while k < len(bool_df.loc[bool_df.loc[:,0],0]):
i = bool_df.loc[bool_df.loc[:,0],0].index[k] # the bool_df index corresponding to k
if i > 0: # avoid negative indeces
if bool_df.loc[i-1,1]: # Check if the previous entry had a value above 5
bool_df.loc[i,1] = True
k+=1
else:
j=i
while bool_df.loc[j,0]: # find the end of the streak of 1<values<5.
j+=1
bool_df.loc[i:j,1] = bool_df.loc[j,1] # set the whole streak to the value found at the end, either >5 or <1
k = sum(bool_df.loc[bool_df.loc[:,0],0].index<j)
else:
k+=1
</code></pre>