【问题标题】:Error in for loop to calculate a percentagefor循环计算百分比时出错
【发布时间】:2020-12-22 06:19:31
【问题描述】:

我正在尝试使用循环下面的代码来计算关闭和打开的交付公司的 df 中的行数的百分比,但我收到 num_total = lead_df.Status[0] 行的错误,这应该可以给我 # 行就像前面几行的代码一样,但给我一个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)

df 的样子:

 Status | Grubhub 
  Closed    True
   Open     True
   Open     False

我不知道我在 num_total 行中缺少什么,因为在单独的单元格中运行 df[(df['Grubhub']== True)] 时它应该可以工作,它会给我 400 行,谢谢!

【问题讨论】:

  • num_overall = df_overall.Status.iat[0] 工作怎么样?
  • 如果我将 .iat[0] 添加到 num total 和 num total 中,它会显示 TypeError: unsupported operand type(s) for /: 'str' and 'str' @jezrael

标签: python python-3.x pandas data-science


【解决方案1】:

我不知道你为什么要使用.Status,但你可以试试这个。

num_total = len(lead_df)

【讨论】:

  • 抱歉,我添加了 df 的外观或至少 df 中的两个重要列,status 是列名
  • @Chris90 好的,关键错误可能来自lead_df 上的索引未重置。即使您重置索引,然后像以前一样过滤掉 DataFrame,lead_df.Status.iloc[0] 也会返回 Closed,而不是当前的行数。
  • 谢谢,当我运行 df_overall.Status[0] 时,为什么它在我的代码上面的 2 行中起作用?
  • 当我用 len(lead_df) 替换 num_total 代码时,它给了我一个错误,前面的代码显示 num_overall = df_overall.Status[0]
  • 我不太确定我是否理解......你介意发送实际的错误输出吗?
猜你喜欢
  • 1970-01-01
  • 2021-04-23
  • 2018-05-15
  • 2018-12-14
  • 2016-06-15
  • 2016-09-04
  • 2018-01-25
  • 1970-01-01
相关资源
最近更新 更多