pca*_*lho 32 python excel xlrd pandas
我目前正在使用pandas来读取Excel文件并向用户显示其工作表名称,因此他可以选择他想要使用的工作表.问题是文件非常大(70列x 65k行),在笔记本上加载最多需要14秒(CSV文件中的相同数据需要3秒).
我在熊猫的代码是这样的:
xls = pandas.ExcelFile(path)
sheets = xls.sheet_names
Run Code Online (Sandbox Code Playgroud)
我之前尝试过xlrd,但获得了类似的结果.这是我的xlrd代码:
xls = xlrd.open_workbook(path)
sheets = xls.sheet_names
Run Code Online (Sandbox Code Playgroud)
那么,有人能建议一种更快的方法从Excel文件中检索工作表名称而不是读取整个文件吗?
小智 45
您可以使用xlrd库并使用"on_demand = True"标志打开工作簿,以便不会自动加载工作表.
您可以通过与pandas类似的方式检索工作表名称:
import xlrd
xls = xlrd.open_workbook(r'<path_to_your_excel_file>', on_demand=True)
print xls.sheet_names() # <- remeber: xlrd sheet_names is a function, not a property
Run Code Online (Sandbox Code Playgroud)
Dhw*_*hah 13
我已经尝试过 xlrd、pandas、openpyxl 和其他此类库,并且随着读取整个文件时文件大小的增加,所有这些库似乎都需要指数级的时间。上面提到的其他使用“on_demand”的解决方案对我不起作用。以下函数适用于 xlsx 文件。
def get_sheet_details(file_path):
sheets = []
file_name = os.path.splitext(os.path.split(file_path)[-1])[0]
# Make a temporary directory with the file name
directory_to_extract_to = os.path.join(settings.MEDIA_ROOT, file_name)
os.mkdir(directory_to_extract_to)
# Extract the xlsx file as it is just a zip file
zip_ref = zipfile.ZipFile(file_path, 'r')
zip_ref.extractall(directory_to_extract_to)
zip_ref.close()
# Open the workbook.xml which is very light and only has meta data, get sheets from it
path_to_workbook = os.path.join(directory_to_extract_to, 'xl', 'workbook.xml')
with open(path_to_workbook, 'r') as f:
xml = f.read()
dictionary = xmltodict.parse(xml)
for sheet in dictionary['workbook']['sheets']['sheet']:
sheet_details = {
'id': sheet['sheetId'], # can be @sheetId for some versions
'name': sheet['name'] # can be @name
}
sheets.append(sheet_details)
# Delete the extracted files directory
shutil.rmtree(directory_to_extract_to)
return sheets
Run Code Online (Sandbox Code Playgroud)
由于所有 xlsx 基本上都是压缩文件,我们提取底层 xml 数据并直接从工作簿中读取工作表名称,与库函数相比,这需要几分之一秒的时间。
基准测试:(在 4 张
6mb xlsx 文件上)Pandas,xlrd: 12 秒
openpyxl: 24 秒
建议方法: 0.4 秒
根据我对标准/流行库的研究,截至 2020 年尚未为xlsx/xls实现这一点,但您可以为xlsb. 无论哪种方式,这些解决方案都应该为您带来巨大的性能改进。对于xls, xlsx, xlsb.
下面是基准上〜10Mb的xlsx,xlsb文件。
xlsx, xlsfrom openpyxl import load_workbook
def get_sheetnames_xlsx(filepath):
wb = load_workbook(filepath, read_only=True, keep_links=False)
return wb.sheetnames
Run Code Online (Sandbox Code Playgroud)
基准: ~ 14 倍速度提升
# get_sheetnames_xlsx vs pd.read_excel
225 ms ± 6.21 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
3.25 s ± 140 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Run Code Online (Sandbox Code Playgroud)
xlsbfrom pyxlsb import open_workbook
def get_sheetnames_xlsb(filepath):
with open_workbook(filepath) as wb:
return wb.sheets
Run Code Online (Sandbox Code Playgroud)
基准: ~ 56 倍速度提升
# get_sheetnames_xlsb vs pd.read_excel
96.4 ms ± 1.61 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
5.36 s ± 162 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Run Code Online (Sandbox Code Playgroud)
笔记:
xlrd 到 2020 年不再维护基于dhwanil-shah的答案,我发现这是最有效的:
import os
import re
import zipfile
def get_excel_sheet_names(file_path):
sheets = []
with zipfile.ZipFile(file_path, 'r') as zip_ref: xml = zip_ref.read("xl/workbook.xml").decode("utf-8")
for s_tag in re.findall("<sheet [^>]*", xml) : sheets.append( re.search('name="[^"]*', s_tag).group(0)[6:])
return sheets
sheets = get_excel_sheet_names("Book1.xlsx")
print(sheets)
# prints: "['Sheet1', 'my_sheet 2']"
Run Code Online (Sandbox Code Playgroud)
xlsb 工作替代方案
import os
import re
import zipfile
def get_xlsb_sheet_names(file_path):
sheets = []
with zipfile.ZipFile(file_path, 'r') as zip_ref: xml = zip_ref.read("docProps/app.xml").decode("utf-8")
xml=grep("<TitlesOfParts>.*</TitlesOfParts>", xml)
for s_tag in re.findall("<vt:lpstr>.*</vt:lpstr>", xml) : sheets.append( re.search('>.*<', s_tag).group(0))[1:-1])
return sheets
Run Code Online (Sandbox Code Playgroud)
优点是:
有待改进: