簡體   English   中英

為什么 Pandas read_excel 函數在 Pyinstaller .exe 中返回錯誤,但在 Python 解釋器下卻沒有?

[英]Why does Pandas read_excel function return an error in Pyinstaller .exe but not under Python interpreter?

我正在使用 Pandas read_excel函數從電子表格中導入數據。 這在 Python 解釋器下運行時工作正常,但是當我使用 PyInstaller 構建一個 exe 時,它​​返回一個 IndexError。

這是演示問題的簡化代碼pandas_test.py

import pandas as pd

filepath = 'C:/Users/User/Documents/Development/Python/PHL/Test Data/Study 
template mock-up.xlsx'
df = pd.read_excel(filepath, sheet_name='Data Entry', index_col=9)
print(df.head())

這在 Python 3.6 和 pandas 0.23.4 和 xlrd 1.1.0 下運行得很好。

當我使用 PyInstaller 構建pandas_test.py ,它成功生成了一個pandas_test.exe ,但出現此錯誤:

 Traceback (most recent call last): File "pandas_test.py", line 4, in <module> File "site-packages\\pandas\\io\\excel.py", line 212, in read_excel File "site-packages\\pandas\\io\\excel.py", line 513, in _parse_excel File "site-packages\\pandas\\io\\parsers.py", line 1912, in TextParser File "site-packages\\pandas\\io\\parsers.py", line 764, in __init__ File "site-packages\\pandas\\io\\parsers.py", line 995, in _make_engine File "site-packages\\pandas\\io\\parsers.py", line 2021, in __init__ File "site-packages\\pandas\\io\\parsers.py", line 2772, in _get_index_name File "site-packages\\pandas\\io\\parsers.py", line 3084, in _clean_index_names IndexError: list index out of range [17264] Failed to execute script pandas_test

我已經閱讀了 PyInstaller 的輸出,但沒有明顯相關的內容:

887 INFO: PyInstaller: 3.3.1
887 INFO: Python: 3.6.2
889 INFO: Platform: Windows-10-10.0.17134-SP0
892 INFO: wrote C:\Users\User\Documents\Development\Python\PandaTest\pandas_test.spec

如果找不到某個模塊,我可以理解,但為什么只在部署的代碼中出現 IndexError?

我遇到了與您類似的錯誤,但在我的情況下,在我運行它以獲取以下腳本的“檢測到致命錯誤”之前沒有警告(Excelfile.parse 等效於 read_excel(ExcelFile, ...),只需嘗試查看 Pyinstaller是否可以使用它)

import xlrd
import pandas as pd
from os.path import join, isfile
from os import environ
if isfile(join(environ['USERPROFILE'],'Downloads','Report_15_13__12_12_2018.xlsx')):
    rd=pd.Excelfile(join(environ['USERPROFILE'],'Downloads','Report_15_13__12_12_2018.xlsx'))
    df1=rd.parse()
    df1.to_excel(join(environ['USERPROFILE'],'Downloads','test.xls'))

我找不到有關如何克服的答案,但是通過從 Pandas 復制代碼( https://github.com/pandas-dev/pandas/blob/v0.24.1/pandas/io/excel.py#L658-L718 )我成功地解決了它。 就我而言,我只有一張紙,但我相信可以輕松支持多張紙。

from xlrd import (xldate, XL_CELL_DATE,
                          XL_CELL_ERROR, XL_CELL_BOOLEAN,
                          XL_CELL_NUMBER,open_workbook)

from datetime import date, datetime, time, timedelta
from pandas import DataFrame
from numpy import array,nan
from os import environ
from os.path import join

book=open_workbook(join(environ['USERPROFILE'],'Downloads','excel_to_read.xls'))
epoch1904 = book.datemode
sheet=book.sheet_by_index(0)
def _parse_cell(cell_contents, cell_typ):
    """converts the contents of the cell into a pandas
        appropriate object"""

    if cell_typ == XL_CELL_DATE:

        # Use the newer xlrd datetime handling.
        try:
            cell_contents = xldate.xldate_as_datetime(
                cell_contents, epoch1904)
        except OverflowError:
            return cell_contents

        # Excel doesn't distinguish between dates and time,
        # so we treat dates on the epoch as times only.
        # Also, Excel supports 1900 and 1904 epochs.
        year = (cell_contents.timetuple())[0:3]
        if ((not epoch1904 and year == (1899, 12, 31)) or
                (epoch1904 and year == (1904, 1, 1))):
            cell_contents = time(cell_contents.hour,
                                    cell_contents.minute,
                                    cell_contents.second,
                                    cell_contents.microsecond)

    elif cell_typ == XL_CELL_ERROR:
        cell_contents = nan
    elif cell_typ == XL_CELL_BOOLEAN:
        cell_contents = bool(cell_contents)
    elif cell_typ == XL_CELL_NUMBER:
        # GH5394 - Excel 'numbers' are always floats
        # it's a minimal perf hit and less surprising
        val = int(cell_contents)
        if val == cell_contents:
            cell_contents = val
    return cell_contents

data = []


for i in range(sheet.nrows):
    row = [_parse_cell(value, typ)
            for value, typ in zip(sheet.row_values(i),
                                    sheet.row_types(i))]
    data.append(row)
NoOfColumns=len(sheet.row_values(i))
NoOfRows=sheet.nrows-1
DataFrame(array(data[1:]).reshape(NoOfRows,NoOfColumns),columns=data[0]).to_excel(join(environ['USERPROFILE'],'Desktop','test.xlsx'),index=False, engine='xlsxwriter')

我也遇到了這個問題。 就我而言,我通過在 virtualenv 中安裝 xlrd 和 openpyxl 來修復它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM