how do i count the number of cycles per 1.5 seconds on python?

372 views Asked by At

I have a column on time and a column with binary data. every time the binary number changes from 1 to 0, that's 1 cycle. i'd like to add up the number of cycles per 1.5 second.

something like

first 1.5s - 1,0,1,0 -> 2 cycles

second 1.5s - 1,0 -> 1 cycle

third 1.5s - 1,0,1,0,1,0 -> 3 cycles.

thank you!!

2

There are 2 answers

0
RaJa On

Assuming your time is equi-distant, so 1.5s are always e.g. 3 rows, you can easily do that in a loop:

for x in range(0, len(df), 3): #df being your dataframe
    total = df.loc[x:x+3, 'Binary_data'].sum()

Otherwise (not equi-distant), you need to:

  1. convert your time-column to datetime-dtype
  2. Use grouper: df.groupby(pd.Grouper(freq='1.5s')).sum(), with pdbeing pandas
0
Lucas Urban On

Each time a cycle passes, add cycles += 1 into the code:

from time import time, sleep
start = time()
cycles = 0
sleep(0.5)
def cycle_todo(): #Define cycle!
    sleep(0.05)
while True:
    cycle_todo()
    cycles += 1
    print("Average cycles / 1.5 s: {}     ".format(round(cycles/((time()-start)/1.5), 3)),end="")
    print("\r", end="")