首页 > 解决方案 > 将 python 代码与 Django 集成时出现错误 KeyError: (8, 'occured at index 0')。该代码适用于spyder

问题描述

我正在尝试将在 spyder 中独立工作的 python 代码与我在 Atom 中运行的 Django 集成。

下面的代码

import pandas as pd
import datetime
month = request.POST.get('month')
start_month_no = request.POST.get('start_month')
month = int(month)


fin_data = pd.read_excel('C:\Resh\PythonWorkingDir\sample.xlsx', header=0)
fin_data = fin_data.drop(['Clarity Code', 'Additions to Projection if any', 
'Total Projection for the  Month INR',
                          'Invoiced Against Projection', 'Remarks'], axis=1)

fin_data.rename(columns={'SOW No/Work Order Number': 'SOW',
                         'PPM id': 'PPM',
                         'Project Name': 'ProjName'
                         },
                inplace=True)
print(fin_data)
fin_data.fillna(0, inplace=True)

prj_in_month = 5
inv_in_month = 6

for a in range(1, month + 1):
   fin_data[a] = fin_data.apply(lambda x: x[inv_in_month] - x[prj_in_month], axis=1)

   prj_in_month = prj_in_month + 2
   inv_in_month = inv_in_month + 2

   a = a + 1

lamda 函数在 prj_in_month = 5 和 inv_in_month = 6 时起作用,然后它采用列中的值(注 5 和 6 以及位置而不是列名)。但是,当循环第二次运行时,它会给出错误 KeyError: (8, 'occured at index 0') 在我看来,它第二次寻找列名 8 而不是第 8 位。我不想将列名传递给 lamda,而是想传递列位置。

奇怪的是代码在 spyder /pycham 中工作得非常好,但当我在 Django 中的 views.py 中添加它时就不行了。

有人能帮我吗。

谢谢,雷什米

标签: pythondjangodataframe

解决方案


推荐阅读