Home > front end >  Count only first occurrence of each sequence python
Count only first occurrence of each sequence python

Time:05-20

I have some acceleration data that I have set up a new column to give a 1 if the accel value in the accelpos column >=2.5 using the following code

frame["new3"] = np.where((frame.accelpos >=2.5), '1', '0')

I end up getting data in sequences like so

0,0,0,0,1,1,1,1,1,0,0,0,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0

I want to add a second column to give a 1 just at the start of each sequence as follows

0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0

Any help would be much apreciated

CodePudding user response:

I am not familiar with the where function. I guess i might try and help from an algorithmic point of view.

Assume we have a list a = [0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, ..., 0]

From an algorithmic POV if you want to replace each sequence of 1 with a unique one at the begining of such sequence here is what you want to do :

  • parse the list
  • assess whether it is a one or a zero
  • if it is a one then, each following item must be a 0 until you actually have a zero

You might want to have something like this :

a = [0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1]

for i in range(len(a)-1):
    if a[i] == 1 :
        for j in range(1,len(a)-i):
            if a[i j] == 1:
                a[i j] = 0
            else :
                break

CodePudding user response:

You can compare shifted values by Series.shift and get values only for '1', so chain conditions by & for bitwise AND and last casting to integers for True/False to 1/0 mapping:

df = pd.DataFrame({'col':'0,0,0,0,1,1,1,1,1,0,0,0,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0'.split(',')})

df['new'] = (df['col'].ne(df['col'].shift()) & df['col'].eq('1')).astype(int)

Or test difference, but because possible first 1 is necessary replace missing value by original with fillna:

s = df['col'].astype(int)
df['new'] = s.diff().fillna(s).eq(1).astype(int)

print (df)
   col  new
0    0    0
1    0    0
2    0    0
3    0    0
4    1    1
5    1    0
6    1    0
7    1    0
8    1    0
9    0    0
10   0    0
11   0    0
12   1    1
13   1    0
14   0    0
15   0    0
16   0    0
17   1    1
18   1    0
19   1    0
20   1    0
21   1    0
22   1    0
23   1    0
24   1    0
25   1    0
26   1    0
27   0    0
28   0    0
29   0    0
30   0    0
  • Related