首页 > 解决方案 > 如何修复错误:/输入“公司”处的 KeyError?从数据框中选择单行时

问题描述

def input(request):
    if 'pass' in request.POST:
        company = request.POST['pass']
    else:
        company = False
    df = pandas.read_csv('data.csv',index_col = None)
    take = df.groupby('Company').mean()
    table = take[take['Company'] == company]
    table_content = table.to_html(classes = 'table')
    return render(request,'result.html',{'table_content': table_content})

我想以表格形式表示 HTML 中的单行。但是在 /input 'Company' 处出现错误 KeyError。我正在使用 Django。

/输入'公司'处的KeyError

标签: pythondjangopandasdataframe

解决方案


如果你在 python 中有一个字典,并且你想检查一个键/值对是否存在,你应该使用get. 见https://www.programiz.com/python-programming/methods/dictionary/get

所以这也是你应该在你的网络应用程序中做的事情。

例子:

d = {'k':'v'}
val = d.get('k')
if val is None:
  print('not found')
else:
  print('found')

推荐阅读