python - 当表格从可变行开始时,Pandas 读取 Excel

标签 python excel pandas

我有一个包含多张工作表的 Excel 工作簿。我正在尝试迭代地使用 Pandas read_excel() 从每个工作表中读取数据框,以便为每个工作表输出单独的 csv 文件。

def getSheets(inputfile, fileformat):
'''Split the sheets in the workbook into seperate CSV files in to folder
    in the directory. CSV's are named identical to the original sheet names'''
name = getName(inputfile) # get name
try:
    os.makedirs(name)
except:
    pass
# read as df
df1 = pd.ExcelFile(inputfile)
# for each sheet create new file
for x in df1.sheet_names:
    y = x.lower().replace("-", "_").replace(" ","_")
    print(x + '.' + fileformat, 'Done!')
    df2 = pd.read_excel(inputfile, sheet_name=x) #looking for way to dynamically find where the table begins
    filename = os.path.join(name, y + '.' + fileformat)
    if fileformat == 'csv':
        df2.to_csv(filename, index=False)
    else:
        df2.to_excel(filename, index=False)
我遇到的问题是 Excel 工作簿有很多格式。结果是实际表格在每张纸的不同行开始。以下是工作簿中一张工作表的示例:
example sheet
此处表格从第 10 行开始。在同一工作簿的其他工作表中,表格从第 8 行开始,依此类推。有 >50 张纸,表格的第一行从始至终都以不同的方式开始。
我已经阅读了有关使用“skiprows”参数从特定行读取的方法。但是对于我迭代的每张纸,该争论的值(value)都会发生变化。当每个表格从可变行开始时,有没有办法使用 Pandas 读取表格,或者有什么方法可以识别表格在 Excel 工作表中的实际开始位置?

最佳答案

您可以通过在调用 pd.read_excel 之前手动读取 Excel 文件来找到表格的开始位置。 (或其近亲 ExcelFile.parse ):

frames = []

xl = pd.ExcelFile('data.xlsx')
for sheet in xl.book.sheets():
    # Find where a table begins within the first 200 rows of the sheet
    found = False
    for n in range(200):
        if sheet.cell_value(n, 0) == 'ID':
            found = True
            break
    if not found:
        raise ValueError('Cannot find the table')
    
    # Read the table
    frames.append(xl.parse(sheet.name, skiprows=n))

关于python - 当表格从可变行开始时,Pandas 读取 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64564569/

相关文章:

Python - 无法连接到数据库

python - 属性错误 : module 'pandas' has no attribute 'read_csv' Python3. 5

python - 有没有办法在 pandas 数据帧上并行化这个循环?

python - pandas 数据框中的列到行

vba - 如何关闭用户窗体并在 VBA 中打开另一个用户窗体

python - 停止 Pandas ExcelWriter() 创建额外的列

python - 使用 Flask 从发布请求保存文件仅在本地有效

python - 由两个分类列定义的 pandas 数据框的加权时间聚合

javascript - 如何使用 Office.js 获取单元格的格式

javascript - 从网站上读取信息并存储在 excel 文件中