python - 如何修复错误:/输入“公司”处的 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
解决方案
如果你在 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')
推荐阅读
- python - Discord content
- angular - How to replace the ag-grid sort arrow icon with my custom svg icon
- angular - Base routes are always empty with rendertron
- javascript - bootstrap datepicker start at a specific date
- r - Replace column with the most recently available data (replace nested forloop with purrr)
- csv - 批处理文件将 csv/文本文件的第二行/行移动到另一个 csv/文本文件(必须跳过 csv/文本文件的第一行)
- python - I want to parse and upload a large csv file into a msql database, but its taking forever. Python/Django
- c++ - Output stream not working without any error
- google-cloud-firestore - Cloud Function Deployment - TypeError: instance.INTERNAL.registerComponent is not a function
- c# - How can I determine the length a windows login took for a user?