【问题标题】:Loading first 100 rows of excel加载前 100 行 excel
【发布时间】:2019-05-29 11:30:33
【问题描述】:

我有一个非常大的 excel 文件,我只想加载前 100 行。看来pandas做的不是很好,在下面的命令中加载大约需要10秒:

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

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

【问题讨论】:

  • 延长时间可能是“import pandas as pd”这一行。在我的电脑上也需要 4-5 秒。这是一个巨大的图书馆。如果 10 秒太长,请尝试 xlrd 模块甚至 csv 模块(并保存为 csv - 知道您会丢失一些功能)。
  • 作为对@NickDima 上述评论的回应,pandas docs 中说您可以使用 xlrd 引擎来读取文件。
  • @mariogarcc 如果您必须完全导入熊猫,问题仍然存在
  • @NickDima 对不起,为什么导入 pandas 有问题?我只是说,您可以尝试使用 pandas 提供的 xlrd 引擎,而不是导入其他模块。如果它解决了问题,很好;如果没有,我们可以搜索其他解决方案。
  • 导入一个模块需要时间,而pandas是一个相当大的模块。不过应该不会有太大的不同,在我的笔记本电脑上导入 pandas 只需不到一秒钟的时间,而且在我的 PC 上基本上是即时的。

标签: python excel pandas


【解决方案1】:

原因

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

xlrd 确实提供了load worksheets on demand 的可能性,但不幸的是,如果您的所有数据都在一个非常大的 Excel 工作表中(另外,这个选项似乎不支持 @ 987654332@ 文件)。

解决方案

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 行在我的机器上只需 pd.read_excel(nrows=100) 执行相同操作需要 >2 分钟。

【讨论】:

  • 这太棒了,谢谢你的建议。这是我们最终要走的路线。感谢您的帮助。
  • .xlsx 文件不支持 xlrd 中的 on_demand 选项。
【解决方案2】:

sxl 模块是专门为此目的而创建的。获取工作表的前 100 行:

import sxl

wb = sxl.Workbook('myfile.xlsx')
ws = wb.sheets[1]  # this gets the first sheet
data = ws.head(100)

【讨论】:

  • 谢谢,我去看看。我认为openpyxl 工作得很好。你有使用 sxl 和 openpyxl 的经验吗?
  • 实际上,我对这两种方法的经验都相对较少。我几乎总是使用 xlrd。我最喜欢它的 API,如果您确实 需要加载所有数据,它似乎是最有效的,而我几乎总是这样做。 sxl 的优点是非常小,API 很简单。因此,它易于使用、易于理解,并且在必要时易于调整。 openpyxl 的优点是功能齐全,功能完善,可以读写。 (我使用 xlrd 和 XlsxWriter 的组合而不是 openpyxl。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
  • 2012-11-07
  • 1970-01-01
相关资源
最近更新 更多