【问题标题】:Pandas read excel and skip cells with strikethrough熊猫阅读 excel 并用删除线跳过单元格
【发布时间】:2020-04-18 20:46:20
【问题描述】:

我必须处理一些从外部来源收到的xlsx。有没有更直接的方法可以在pandas 中加载xlsx,同时也跳过带有删除线的行?

目前我必须这样做:

import pandas as pd, openpyxl

working_file = r"something.xlsx"

working_wb = openpyxl.load_workbook(working_file, data_only=True)

working_sheet = working_wb.active

empty = []

for row in working_sheet.iter_rows("B", row_offset=3):
    for cell in row:
        if cell.font.strike is True:
            p_id = working_sheet.cell(row=cell.row, column=37).value
            empty.append(p_id)

df = pd.read_excel(working_file, skiprows=3)
df = df[~df["ID"].isin(empty)]
...

这有效,但只能通过两次检查每个 excel 表。

【问题讨论】:

  • 读取文件时数据框如何显示 - 带有删除线的行,它们看起来不同吗?被破坏?还是像其他人一样的普通数字?图片或一些可重复的示例可能会有所帮助

标签: python-3.x pandas openpyxl


【解决方案1】:

最终继承了 pd.ExcelFile_OpenpyxlReader。这比我想象的要容易:)

import pandas as pd
from pandas.io.excel._openpyxl import _OpenpyxlReader
from pandas._typing import Scalar
from typing import List
from pandas.io.excel._odfreader import _ODFReader
from pandas.io.excel._xlrd import _XlrdReader

class CustomReader(_OpenpyxlReader):
    def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]:
        data = []
        for row in sheet.rows:
            first = row[1] # I need the strikethrough check on this cell only
            if first.value is not None and first.font.strike: continue
            else:
                data.append([self._convert_cell(cell, convert_float) for cell in row])
        return data

class CustomExcelFile(pd.ExcelFile):

    _engines = {"xlrd": _XlrdReader, "openpyxl": CustomReader, "odf": _ODFReader}

设置自定义类后,现在只需像普通的ExcelFile 一样传递文件,将引擎指定给openpyxl,瞧!带有删除线单元格的行已消失。

excel = CustomExcelFile(r"excel_file_name.xlsx", engine="openpyxl")

df = excel.parse()

print (df)

【讨论】:

    【解决方案2】:

    在这种情况下,我不会使用 Pandas。只需使用 openpyxl,从工作表的 end 开始工作并相应地删除行。从工作表的末尾向后工作意味着您在删除行时不会受到副作用的影响。

    【讨论】:

    • 不幸的是,有很多熊猫操作我没有包括在内,因为它与问题无关。不过感谢您的建议。
    • 整理好行后,您仍然可以将内容传递到数据框中。这将比您当前的方法更容易、更可靠。
    • 我最终对pd.ExcelFile 进行了子分类,以通过openpyxl 跳过删除线单元格。
    猜你喜欢
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 2020-11-07
    相关资源
    最近更新 更多