У меня ошибка **** KeyError: «Средневзвешенное значение» при использовании Spyder - PullRequest
0 голосов
/ 07 мая 2020

Когда я запускаю свой код, у меня возникает ошибка. Я пробовал на другом компьютере, код работает правильно. Что я сделал недавно: это случилось после того, как я обновил свой Spyder. У меня сейчас Spyder 4.0.1.

*** Сообщение об ошибке:

Python 3.7.6 (default, Jan  8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 7.12.0 -- An enhanced Interactive Python.

runfile('C:/Users/******/Python/Codes/Check/check_cust_no.py', wdir='C:/Users/****/Python/Codes/Check')
Traceback (most recent call last):

  File "C:\Users\*****\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 2646, in get_loc
    return self._engine.get_loc(key)

  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\hashtable_class_helper.pxi", line 1618, in pandas._libs.hashtable.PyObjectHashTable.get_item

  File "pandas\_libs\hashtable_class_helper.pxi", line 1626, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'Weighted average'

Я не знаю, как решить эту проблему. Я думаю, что это связано с lib pandas, но я не знаю, как работать с base.py

*** Код:

import pandas as pd
import numpy as np
import calendar
import datetime
import tkinter as tk
from tkinter import filedialog
import openpyxl


root=tk.Tk()
root.lift()
root.attributes("-topmost", True)
check_file_path = filedialog.askopenfilename(title='Select the check file in .txt format')
root.withdraw()

with open(check_file_path) as f:
    lines = f.readlines()
f.close()


# Write the relevant parts to dataframe
df = pd.DataFrame(index = range(len(lines)), columns = ['Day', 'Month', 'Year', 'Amount', 'Customer', 'Weighted average', 'Period', 'Check maturity', 'Customer number'])
for i in range(len(lines)):
    x = lines[i]
    df.iloc[i,0] = x[60:62]
    df.iloc[i,1] = x[62:64]
    df.iloc[i,2] = x[64:68]
    df.iloc[i,3] = np.float64((x[130:143]))
    df.iloc[i,4] = x[153:185].strip()
    df.iloc[i,8] = int(x[90:98])



# Elegant fixes and dataframe shaping
df['Date'] = pd.to_datetime(df[['Day', 'Month', 'Year']])
df = df[['Customer', 'Customer number', 'Period', 'Amount', 'Date', 'Check maturity','Weighted average']]
df['Amount'] = df['Amount'].apply(pd.to_numeric)

for i in range(len(df)):
    df.loc[i, 'Period'] = df.loc[i, 'Date'].strftime('%m-%Y')
    df.loc[i, 'Check maturity'] = pd.Timestamp.date(df.loc[i, 'Date'])




# WA calculation
for i in range(len(df)):
    ts_utc = df.loc[i, 'Date']
    ts_px = calendar.timegm(ts_utc.utctimetuple())
    ts_px = ts_px * df.loc[i, 'Amount']
    df.loc[i, 'Weighted average'] = int (ts_px)

df.drop('Date', axis = 1, inplace = True)




# WACD calculation
df1 = (df.groupby(['Customer', 'Customer number', 'Period']).sum()).reset_index()

df1['WACD']= ''
# Due date calculation
for i in range(len(df1)):
    df1.loc[i, 'WACD'] = datetime.datetime.fromtimestamp(df1.loc[i, 'Weighted average'] / df1.loc[i, 'Amount'])




# Comparison
root=tk.Tk()
root.lift()
root.attributes("-topmost", True)
body_path = filedialog.askopenfilename(title='Select the report file')
root.withdraw()

body = pd.read_excel(body_path)
df1['Amount difference'] = ''
df1['WACD difference'] = ''
df1['Row_ID'] = ''
for i in range(len(body)):
    for j in range(len(df1)):
      if df1.loc[j,'Customer number'] == body.loc[i,'Customer number'] and df1.loc[j,'Period'] == body.loc[i, 'Period']:
            df1.loc[j, 'Amount difference'] = df1.loc[j, 'Amount'] - body.loc[i, 'Amount']
            df1.loc[j, 'WACD difference'] = (df1.loc[j, 'WACD'] - body.loc[i, 'WACD']).days
            df1.loc[j, 'Row_ID'] = i




# Writer
wb = openpyxl.load_workbook('%s' % body_path)
ws = wb.active

max_rows = ws.max_row
while ws.cell(row=max_rows, column=2).value == None:
        ws.delete_rows(max_rows,1)
        max_rows = ws.max_row

ws.cell(row = 1, column = 8).value = body.keys()[2]  # Amount
ws.cell(row = 1, column = 9).value = body.keys()[4]  # WA
ws.cell(row = 1, column = 10).value = body.keys()[5]  # WACD
ws.cell(row = 1, column = 12).value = 'Amount difference'
ws.cell(row = 1, column = 12).value = 'WACD difference'


for i in range(len(df1)):
    x = df1.loc[i, 'Row_ID']
    if x == '':
        continue

    ws.cell(row = int(x)+2, column = 8).value = df1.loc [i, 'Amount']
    ws.cell(row = int(x)+2, column = 9).value = df1.loc [i, 'Weighted average'] ```
    ws.cell(row = int(x)+2, column = 10).value = df1.loc [i, 'WACD']
    ws.cell(row = int(x)+2, column = 12).value = df1.loc [i, 'Amount difference']
    ws.cell(row = int(x)+2 , column = 13).value = df1.loc [i, 'WACD difference']

wb.save('%s' % body_path)

1 Ответ

0 голосов
/ 07 мая 2020
• 1000 вы просто помещаете строку, которая не соответствует метке. взгляните на Pandas документацию на loc []
...