gpt4 book ai didi

python - 加载前 100 行 excel

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:13 25 4
gpt4 key购买 nike

我有一个非常大的 excel 文件,我只想加载前 100 行。 pandas 似乎做得不好,因为在以下命令中加载大约需要 10 秒:

pd.read_excel('excel/BigFile.xlsx', nrows=100)

它似乎花费了与根本不传递 nrows 参数相同的时间。有没有办法“快速”读取 excel 文件的前 100 行?如果不是在 pandas 中,是否有其他工具可以更好地做到这一点?

最佳答案

原因

pandas 使用 xlrd引擎盖下的包,用于读取 excel 文件。 xlrd 的默认行为似乎是将整个 excel 工作簿加载到内存中,而不管最后读出的是什么数据。这可以解释为什么您在使用 pd.read_excel()nrows 参数时没有注意到加载时间的减少。 .

xlrd 确实提供了 load worksheets on demand 的可能性相反,但不幸的是,如果您的所有数据都在一个非常大的 excel 工作表中(此外,此选项似乎不支持 .xlsx 文件),这将无济于事。

解决方案

excel解析包openpyxl确实提供了 load individual excel rows on demand 的可能性(即只有需要的 excel 行被加载到内存中)。通过一些自定义代码,可以利用 openpyxl 将您的 excel 数据检索为 pandas 数据框:

import openpyxl
import pandas as pd


def read_excel(filename, nrows):
"""Read out a subset of rows from the first worksheet of an excel workbook.

This function will not load more excel rows than necessary into memory, and is
therefore well suited for very large excel files.

Parameters
----------
filename : str or file-like object
Path to excel file.
nrows : int
Number of rows to parse (starting at the top).

Returns
-------
pd.DataFrame
Column labels are constructed from the first row of the excel worksheet.

"""
# Parameter `read_only=True` leads to excel rows only being loaded as-needed
book = openpyxl.load_workbook(filename=filename, read_only=True, data_only=True)
first_sheet = book.worksheets[0]
rows_generator = first_sheet.values

header_row = next(rows_generator)
data_rows = [row for (_, row) in zip(range(nrows - 1), rows_generator)]
return pd.DataFrame(data_rows, columns=header_row)


# USAGE EXAMPLE
dframe = read_excel('very_large_workbook.xlsx', nrows=100)

使用此代码加载 >100MB 单页 excel 工作簿的前 100 行在我的机器上仅需 <1 秒,而使用 pd.read_excel(nrows=100) 执行相同操作则需要>2 分钟。

关于python - 加载前 100 行 excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54012750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com