如何修复“ IndexError:单个位置索引器超出范围”?

时间:2019-12-29 22:33:22

标签: python python-3.x pandas dataframe parsing

我看到了一些类似的问题,但答案没有帮助。我有生以来第一次做解析器,似乎犯了一个错误。我有一个数据文件,分为月和年,每个月里面都有相同的列,具有不同的值。每个新月都以21个单元格开始。我做了一个解析器一个月。我需要对表中的下一个重复此操作。我试图制定一种方法来做到这一点。我将整个解析器放入一个循环,该循环将重复进行,直到单元用完为止。但是,执行此操作时遇到错误。

这是我的代码。

import pandas as pd
import numpy as np
from datetime import date, datetime
import datetime as DT
import time
import calendar
from pandas import DataFrame

# Empty dataframe where processed months are loaded
allmonths = pd.DataFrame()

dictionary = dict(December='12', January='01',February='02', March='03', April='04', May='05', June='06', July='07',
                  August='08', September='09', October='10', November='11')

df = pd.read_excel('C:/Users/shevc/Desktop/zbl/Shakh.xlsx')
# cut off excess caps from the data frame to count values
dfnew = df.iloc[3:, 4:]
# print(dfnew)

# the iterator takes the maximum index value in the table
perem = dfnew.index[-1]
prov = dfnew.index[-1]
#print(perem)

#variables to jump through cells
formonths = 0
forDF1 = 0
forDF2 = 0

for i in range(0, perem - 1):
    if perem == prov:
        formonths += 3
        forDF1 += 3
        forDF2 += 24
    else:
        formonths += 21
        forDF1 += 21
        forDF2 += 21

    # if the file ends, then exit the loop
    if perem < 0 | formonths > perem | forDF1 > perem | forDF2 > perem:
        break

    # for working with month
    months = df.iloc[formonths]['534']
    s = pd.Series(months)
    # print(months)

    # there is a split of the month and year and extraction of 1 and 2 elements
    months.split()
    # print(months)
    month = months.split()[0]
    year = months.split()[-1]
    # print(year)

    # dictionary and month comparison
    if month in dictionary.keys():
        result = dictionary[month]

    # converted to time format
    resulttimemonth = time.strptime(result, '%m')
    moonth = resulttimemonth.tm_mon
    resulttimeyear = time.strptime(year, '%Y')
    yeear = resulttimeyear.tm_year

    # find out the number of days in the month of the desired year
    days_in_month = calendar.monthrange(yeear, moonth)[1]
    #print(days_in_month)

    dti = str(days_in_month) + '.' + str(moonth) + '.' + str(yeear)


    new = df.T
    newest = new.iloc[6:, forDF1:forDF2]
    newest['date'] = dti
    newest.index = np.arange(len(newest))
    newest.columns = ['Qн ТМ', 'F вращ ТМ', 'ТМ Qж(тн)', 'Qж(тн)', 'Обв', 'Qж', 'Обв ХАЛ', 'Qж ТМ', 'F', 'Dшт',
                      'Qж ТМ (исх)', 'Рбуф ТМ', 'Qг (АГЗУ)', 'Ртр', 'Рбуф ТМ', 'ГФ', ' Обв ТМ ручн', 'Qн ТМ ручн',
                      'Pзаб(PпрTM)', 'Рзат ТМ', 'Примечание', 'Дата']
    #print(newest)

    # load each new month into a common dataframe one after another
    itog = allmonths.append(newest)

    perem = perem - 21


# make a new excel file from dataframe
itog.to_excel('C:/Users/shevc/Desktop/zbl/result.xlsx', startrow=0, index=False)

这是我得到的错误。

Traceback (most recent call last):
  File "C:/Users/shevc/Desktop/збл/Prog1.py", line 45, in <module>
    months = df.iloc[formonths]['534']
  File "C:\Users\shevc\AppData\Local\Temp\Prog1.py\venv\lib\site-packages\pandas\core\indexing.py", line 1424, in __getitem__
    return self._getitem_axis(maybe_callable, axis=axis)
  File "C:\Users\shevc\AppData\Local\Temp\Prog1.py\venv\lib\site-packages\pandas\core\indexing.py", line 2157, in _getitem_axis
    self._validate_integer(key, axis)
  File "C:\Users\shevc\AppData\Local\Temp\Prog1.py\venv\lib\site-packages\pandas\core\indexing.py", line 2088, in _validate_integer
    raise IndexError("single positional indexer is out-of-bounds")
IndexError: single positional indexer is out-of-bounds

How file with data looks like before parsing And what I need to do. It<code>s only for december and with one mistake, that I</code>ll fix later (it`s 31 in all cells, but it will be 1 to 31 from beginning to end)

0 个答案:

没有答案