Reputation: 75
My data is like this:
import numpy as np
import pandas as pd
s = pd.Series([True,True,True,False,True,False, False, True])
and I want to assign the same values(starting from 1) to the "True" rows which are adjacent to each other. And assign 0 to "False" values.
So the final result should be like this:
Here is the code I've written. I do not get any error but it cannot execute the code it seems running forever. (I don't know why!)
s['values'] = None
j = 0
for ii in range(1, len(list1)):
if list1['delay'].iloc[ii] != list1['delay'].iloc[ii-1]:
j += 1
s['values'][ii] = j
(I've started the for loop from 1 since I thought I will change the first value manually)
Please help me with this.
Upvotes: 0
Views: 496
Reputation: 323226
Try this , I break down the steps.:)
import numpy as np
import pandas as pd
s = pd.Series([True,True,True,False,True,False, False, True])
b=s
b=b.astype(int).diff().fillna(0)
b=b.ne(0)
b[~s]=False
b=b.cumsum()+1
b[~s]=0
b
Out[116]:
0 1
1 1
2 1
3 0
4 2
5 0
6 0
7 3
dtype: int32
Or using for loop ..
ll=[]
j=0
for i in range(0, len(s)):
if s[i]:
j += 1
try:
if s[i-1]:
j-=1
ll.append(j)
else:
ll.append(j)
except:ValueError
else:
ll.append(0)
[1]+ll
Out[135]: [1, 1, 1, 0, 2, 0, 0, 3]
Upvotes: 1