[英]Small Excel spreadsheet loading very slowly using with Python, Pandas and openpyxl
我有一個程序正在從Excel電子表格中讀取一些數據(一小塊:〜10張紙,每張紙〜100個單元格),進行一些計算,然后將輸出寫入電子表格中的單元格。
該程序迅速運行,直到我修改為將其輸出寫入與讀取輸入相同的Excel文件中。 以前,我是生成一個新的電子表格,然后將輸出手動復制到原始文件中。
修改后,腳本的運行時間從幾秒鍾跳到了大約7分鍾。 我運行cProfile進行調查並獲得了此輸出,並按累積運行時間排序:
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.001 0.001 440.918 440.918 xlsx_transport_calc.py:1(<module>)
1 0.000 0.000 437.926 437.926 excel.py:76(load_workbook)
1 0.000 0.000 437.924 437.924 excel.py:161(_load_workbook)
9 0.000 0.000 437.911 48.657 worksheet.py:302(read_worksheet)
9 0.000 0.000 437.907 48.656 worksheet.py:296(fast_parse)
9 0.065 0.007 437.906 48.656 worksheet.py:61(parse)
9225 45.736 0.005 437.718 0.047 worksheet.py:150(parse_column_dimensions)
9292454 80.960 0.000 391.640 0.000 functools.py:105(wrapper)
9292437 62.181 0.000 116.213 0.000 cell.py:94(get_column_letter)
18585439 20.881 0.000 98.832 0.000 threading.py:214(__exit__)
18585443 58.912 0.000 86.641 0.000 threading.py:146(acquire)
18585443 56.600 0.000 77.951 0.000 threading.py:186(release)
9293461/9293452 22.317 0.000 22.319 0.000 {method 'join' of 'str' objects}
37170887 15.795 0.000 15.795 0.000 threading.py:63(_note)
21406059 13.460 0.000 13.460 0.000 {divmod}
37170888 12.853 0.000 12.853 0.000 {thread.get_ident}
18585447 12.589 0.000 12.589 0.000 {method 'acquire' of 'thread.lock' objects}
21408493 9.948 0.000 9.948 0.000 {chr}
21441151 8.323 0.000 8.323 0.000 {method 'append' of 'list' objects}
18585446 7.843 0.000 7.843 0.000 {method 'release' of 'thread.lock' objects}
...
...
...
腳本中的相關代碼:
...
from openpyxl import load_workbook
import pandas as pd
...
xlsx = 'path/to/spreadsheet.xlsx'
...
def loadxlsx(fname, sname, usecols=None):
with pd.ExcelFile(fname) as ef:
df = ef.parse(sheetname=sname)
if usecols:
return [df.values[:,col] for col in usecols]
else:
return [df.values[:,col] for col in range(df.shape[1])]
...
data = loadxlsx('path/to/spreadsheet.xlsx')
...
<do computations>
...
book = load_workbook(xlsx)
<write data back to spreadsheet>
...
因此,根據cProfile輸出,罪魁禍首出現在對load_workbook
的調用中。 除了這種觀察,我還有點困惑。 為什么有9000個調用parse_column_dimensions
和1800萬個調用各種線程函數? 還有900萬次調用get_column_letter
?
這是我第一次剖析任何python腳本,所以我不確定此輸出是否正常……不過似乎有些奇怪。
任何人都可以闡明這里可能發生的事情嗎?
我不知道Pandas代碼中發生了什么,但是調用次數是錯誤的。 如果您嘗試僅使用openpyxl打開文件並在適當位置修改單元格,則它應該快得多,因此看起來好像發生了一些不必要的循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.