Python for循环中计算百分比时出错
我尝试在代码下方使用循环来计算配送公司df中关闭和打开的行的百分比,但是我得到了一个错误,行Python for循环中计算百分比时出错,python,python-3.x,pandas,data-science,Python,Python 3.x,Pandas,Data Science,我尝试在代码下方使用循环来计算配送公司df中关闭和打开的行的百分比,但是我得到了一个错误,行num\u total=lead\u df.Status[0]这应该可以为我提供行,就像前面几行代码一样,但是给我一个KeyError:0 leads = ['Closed','Open'] max_status = None max_percent = None for lead in leads: df_overall = df[(df['Status']==
num\u total=lead\u 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行,谢谢 我不知道您为什么要使用.Status
,但您可以试试这个
num\u total=len(lead\u df)
很抱歉,我添加了df的外观,或者至少添加了df中的两个重要列,status是一个列name@Chris90好的,明白了-关键错误可能是由于未在lead_df
上重置索引。即使你重置索引,然后像你那样过滤数据帧,那么lead_df.Status.iloc[0]
将返回Closed
,而不是当前的行数。谢谢,当我运行df_total.Status[0]时,为什么它在我的代码中起到上面两行的作用?当我用len(lead_df)替换num_total代码时它给了我一个错误,前面的代码是num_-overall=df_-overall.Status[0]我不太确定我是否理解。。。你介意发送实际的错误输出吗?Howw workingnum_-total=df_-total.Status.iat[0]
?如果我将.iat[0]添加到num-total和num-total中,它会显示TypeError:/:'str'和'str'@jezrael不支持的操作数类型