Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counter for multiple tuple conditions

I have a tuple..

for i in my_tup:
   print(i)

Output:

   (Transfer, 0:33:20, Cycle 1)                 
   (Transfer, 0:33:10, Cycle 1)                    
   (Download, 0:09:10, Cycle 1)          
   (Transfer, 0:33:10, Cycle 1)                   
   (Download, 0:13:00, Cycle 1)            
   (Download, 0:12:30, Cycle 2)           
   (Transfer, 0:33:10, Cycle 2)              
   (Download, 0:02:00, Cycle 2)            
   (Transfer, 0:33:00, Cycle 2)              
   (Transfer, 0:33:00, Cycle 2)               
   (Transfer, 0:33:00, Cycle 2)            
   (Transfer, 0:32:40, Cycle 2)       

I am trying to count the number of occurrences of 'Transfer' PER Cycle category. I.e. How many Transfer occurrences are in cycle 1, how many in cycle 2, etc...

I can work it out for the first cycle but not those after this.. (there are many more cycles in the real output).

accumulatedList = []
count = 0
for i in range(0 len(my_tup)):
     if my_tup[i][0] == 'Transfer' and my_tup[i][2] == 'Cycle 1':
          count +=1
     accumulatedList.append(count)

Not sure how to do it for other others too.

like image 548
arsenal88 Avatar asked Nov 18 '25 20:11

arsenal88


2 Answers

Using pandas library it is straightforward:

import pandas as pd
df = pd.DataFrame(my_tup, columns=['Category', 'TimeSpan', 'Cycle'])
g = df.groupby(['Category', 'Cycle']).size()

It returns:

Category  Cycle  
Download  Cycle 1    2
          Cycle 2    2
Transfer  Cycle 1    3
          Cycle 2    5
dtype: int64

If your concern is only about transfer, slice it using index:

g['Transfer']

Cycle
Cycle 1    3
Cycle 2    5
dtype: int64
like image 165
jlandercy Avatar answered Nov 21 '25 10:11

jlandercy


You can use collections.Counter for an O(n) solution.

from collections import Counter

c = Counter()

for cat, time, cycle in lst:
    if cat == 'Transfer':
        c[cycle] += 1

Result

Counter({'Cycle 1': 3,
         'Cycle 2': 5})

Setup

lst =  [('Transfer', '0:33:20', 'Cycle 1'),                 
        ('Transfer', '0:33:10', 'Cycle 1'),        
        ('Download', '0:09:10', 'Cycle 1'),        
        ('Transfer', '0:33:10', 'Cycle 1'),                 
        ('Download', '0:13:00', 'Cycle 1'),          
        ('Download', '0:12:30', 'Cycle 2'),         
        ('Transfer', '0:33:10', 'Cycle 2'),            
        ('Download', '0:02:00', 'Cycle 2'),          
        ('Transfer', '0:33:00', 'Cycle 2'),            
        ('Transfer', '0:33:00', 'Cycle 2'),             
        ('Transfer', '0:33:00', 'Cycle 2'),          
        ('Transfer', '0:32:40', 'Cycle 2')]

Explanation

  • Use a collections.Counter object to increment a cycle key each time the category is "Transfer".
like image 21
jpp Avatar answered Nov 21 '25 10:11

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!