marbr51
marbr51

Reputation: 23

Counting loops/cycles of numbers in Python

Trying to count machine cycles. I need help populating the ID column with some Python code. Thanks for your help.

Every time the Cycle restarts at 1, I would like ID to represent that new cycle from 1 to N.

    Cycle   ID
       1    1
       2    1
       …    1
      35    1

       1    2
       2    2
       …    2
     457    2

       1    3
       2    3
       …    3
     128    3

Upvotes: 0

Views: 3266

Answers (3)

PM 2Ring
PM 2Ring

Reputation: 55469

Just for fun, here's an unreadable nested list comprehension / generator expression. :)

from itertools import groupby

cycle = [1, 2, 3, 4, 5, 6, 1, 2, 3, 1, 2, 3, 4]
a = [(v, i) for i, u in enumerate(([t[1] for t in g] 
    for _, g in groupby(enumerate(cycle), lambda t:t[1]-t[0])), 1) for v in u]

print(a)
for t in zip(*a):
    print([*t])

output

[(1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (1, 2), (2, 2), (3, 2), (1, 3), (2, 3), (3, 3), (4, 3)]
[1, 2, 3, 4, 5, 6, 1, 2, 3, 1, 2, 3, 4]
[1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3]

This code will go to a new ID number whenever there's a break in the sequence of numbers in cycle, the new subsequence doesn't have to restart at 1.

Upvotes: 5

zipa
zipa

Reputation: 27869

Lets say that you have an array cycle with these elements:

cycle = [1,2,3,4,5,6,1,2,3,1,2,3,4]

This will give you desired output:

ID = []
i = 0
for n in cycle:
    if n == 1:
        i += 1
    ID.append(i)
#[1,1,1,1,1,1,2,2,2,3,3,3,3]

And given that this is exact same solution as the other answer, here's a fun one:

i = 0
def makeID():
    global i
    i += 1
    return i
ID = [makeID() if n == 1 else i for n in cycle]

Upvotes: 3

jaguar
jaguar

Reputation: 152

This code should work, assuming cycle is available as a list:

id_count = 0 #make a counter for the id
id_list = [] # create an empty list
for i in cycle: # loop to iterate through cycle
     if i == 1: # checks if 1 is the number
         id_count += 1 # increase the counter
     id_list.append(i) # add the id to the list

This code will create a list of ids for each item in cycle. Hope this helps!

Upvotes: 2

Related Questions