Chris90
Chris90

Reputation: 1998

Error in for loop to calculate a percentage

I am trying below code with a loop to calculate the percentage of # of rows in df of delivery company that is closed and open, but I get an error for the line num_total = lead_df.Status[0] this should work to give me # rows just like the code a few lines prior but is giving me error with a KeyError: 0

leads = ['Closed','Open']
    max_status = None
    max_percent = None
    for lead in leads:
        df_overall = df[(df['Status']== lead)]
        num_overall = df_overall.Status[0]
        lead_df = df[(df['Grubhub']== True)]
        num_total = lead_df.Status[0]
        percentage_overall = num_overall / num_total
       
        
        if max_status is None: 
            
            
            
            print(lead, percentage_overall)

Where the df looks like:

 Status | Grubhub 
  Closed    True
   Open     True
   Open     False

I dont know what I am missing in the num_total line as it should work when run df[(df['Grubhub']== True)] in a separate cell it gives me 400 rows, thanks!

Upvotes: 0

Views: 63

Answers (1)

Spencer Tibbitts
Spencer Tibbitts

Reputation: 96

I'm not familiar with why you'd want to use .Status, but you can try this instead.

num_total = len(lead_df)

Upvotes: 1

Related Questions