在python pandas中动态跳过excel的前空白行

2024-09-28 22:23:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python中的pandas读取excel文件的多个表。 我有三个案子

  1. 某些工作表包含来自第1行的数据
osht=pd.DataFrame(filename+sheetname)

delimited table Example: 
Country;Company;Product
US;ABC;XYZ
US;ABD;XYY
  1. 有的表前有n个空行,有的表有摘要 我知道使用skip_blank我可以去除顶部空白行,但顶部空白行的数量在本质上是不固定的,可能是3、4或8
delimited table Example: 
;;
;;
;;
Country;Company;Product
US;ABC;XYZ
US;ABD;XYY
  1. 表1列中的表格我试图阅读所有这些表格,但不知道如何阅读 -有没有办法从第三行的摘要结尾,第四行是我的表格标题,第一列的标题是“国家”
delimited table Example: 

Product summary table for East region;;
Date: 1st Sep, 2016;;
;;
Country;Company;Product
US;ABC;XYZ
US;ABD;XYY

Tags: 标题pandasexampletableproductcountrycompany表格
1条回答
网友
1楼 · 发布于 2024-09-28 22:23:53

我将提出以下算法:

  1. 读整张桌子
  2. 将不包含缺失值的第一行视为标题
  3. 删除标题上方的所有行

这个代码对我来说没问题:

import pandas as pd
for sheet in range(3):
    raw_data = pd.read_excel('blank_rows.xlsx', sheetname=sheet, header=None)
    print(raw_data)
    # looking for the header row
    for i, row in raw_data.iterrows():
        if row.notnull().all():
            data = raw_data.iloc[(i+1):].reset_index(drop=True)
            data.columns = list(raw_data.iloc[i])
            break
    # transforming columns to numeric where possible
    for c in data.columns:
        data[c] = pd.to_numeric(data[c], errors='ignore')
    print(data)

根据您的示例,它使用this toy data sample。从原始数据帧

^{pr2}$

脚本生成相同的表

  Country Company Product
0      US     ABC     XYZ
1      US     ABD     XYY

相关问题 更多 >