如何在python中修复'IndexError:单位置索引器越界'?

时间:2019-10-20 20:00:24

标签: python dataframe tkinter

我正在尝试使用带有Excel文件的GUI程序。向用户提供了写入excel文件中的数据,如果他按accept,它将把该数据定向到一个表中。如果不是-另一张桌子。我试图以任何我可以在stackoverflow中找到的方式解决它,但是这些似乎都无法解决我的问题。我很乐意提供帮助。

我一直遇到

的问题
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\roniz\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:/Users/roniz/PycharmProjects/emun/manual_validation.py", line 187, in accept_query
    self.accepted.append(self.df.iloc[self.num]['bizid'])
  File "C:\Users\roniz\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\core\indexing.py", line 1424, in __getitem__
    return self._getitem_axis(maybe_callable, axis=axis)
  File "C:\Users\roniz\AppData\Local\Programs\Python\Python37\lib\site-packages\pandas\core\indexing.py", line 2157, in _getitem_axis
    self._validate_integer(key, axis)
  File "C:\Users\roniz\AppData\Local\Programs\Python\Python37\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

如果不是那个,我得到的只是写的不同而已。

我试图将数据作为单行字典进行传输,我试图在代码的不同位置进行数据传输。

import tkinter as Tkinter
import googlemaps
import pandas as pd
import requests


class Application(Tkinter.Frame):
    def __init__(self, master):
        Tkinter.Frame.__init__(self, master)
        self.parent = master
        frame = Tkinter.Frame(self)

        self.df = pd.read_excel('checkformanual.xlsx', sheet_name="Sheet1", header=0)
        self.num = 0
        self.gpi = self.df.iloc[self.num]['googleid']  # @todo: lo#

        self.accepted = []
        self.declined = []

        self.butt1 = Tkinter.Button(frame, text='Accept', command=self.accept_query)
        self.butt2 = Tkinter.Button(frame, text='Decline', command=self.decline_query)

        frame.pack(fill=Tkinter.BOTH, expand=1, side=Tkinter.BOTTOM)
        self.pack(fill=Tkinter.BOTH, expand=1)

    def accept_query(self):
        self.num += 1
        self.accepted.append(self.df.iloc[self.num]['bizid'])

    def decline_query(self):
        self.num += 1
        self.declined.append(self.df.iloc[self.num]['bizid'])

def main():
    root = Tkinter.Tk()
    app = Application(root)
    app.mainloop()

    accepteddf = app.df[app.df['bizid'].isin(app.accepted)]
    declineddf = app.df[app.df['bizid'].isin(app.declined)]

    accepteddf.to_excel("accepted.xlsx", index=False)
    declineddf.to_excel("declined.xlsx", index=False)

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

问题似乎出在此功能中:

def accept_query(self):
        self.num += 1
        self.accepted.append(self.df.iloc[self.num]['bizid'])

具体来说,用iloc[self.num]。如果提供的整数索引(在这种情况下为IndexError)超出范围,则此操作将引发self.num异常。您在追加到self.num之前先增加self.accepted的事实似乎令人怀疑,但这也许是故意的。无论如何,如果至少没有看到excel文件的屏幕截图,就很难进一步诊断问题。