【问题标题】:How to skip rows based on regex with pandas.read_excel?如何使用 pandas.read_excel 跳过基于正则表达式的行?
【发布时间】:2017-11-04 01:58:54
【问题描述】:

我正在尝试使用 pandas.read_excel 读取 excel 表。它的 skiprows 参数允许通过提供行号来跳过行。但是,我们如何根据模式匹配跳过行?我有不同的 Excel 表,其中我需要跳过的行数是可变的,因此提供行数不适用于我的用例。有没有办法我可以提供一个模式 - 例如跳过包含特定字符串的行之前的所有行(比如“测试”)?如果这不能用 pandas read_excel 完成,是否有另一种解决方法可以以这种方式将 excel 读入数据框?任何建议将不胜感激。谢谢。

【问题讨论】:

  • 您可以创建一个引用模式索引的列表,然后使用这些索引中的每一个作为skip_rows 的参数进行循环,但没有样本数据和我们无法提供的模式更“具体”的答案

标签: python excel pandas


【解决方案1】:

我的建议是将整个 Excel 表读入数据框,然后删除不需要的行。举个简单的例子:

import pandas as pd

# Read out first sheet of excel workbook
df = pd.read_excel('workbook.xlsx')

# Find label of the first row where the value 'Test' is found (within column 0)
row_label = (df.iloc[:, 0] == 'Test').idxmax()

# Drop all rows above the row with 'Test'
df = df.loc[row_label:, :]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 2011-10-15
    • 2016-06-07
    • 1970-01-01
    相关资源
    最近更新 更多