如何用Python(含PySpark)自动跳过Excel/CSV无关行直至找到表头行
Python 实现方案
处理 Excel 文件(使用 pandas)
核心思路是先扫描文件定位目标表头行的位置,再从该行开始读取完整数据。
import pandas as pd # 加载 Excel 文件 excel_file = pd.ExcelFile("your_target_file.xlsx") # 先以无表头模式读取工作表,用于扫描 temp_sheet = excel_file.parse(sheet_name=0, header=None) # 遍历行,找到以"G/L"开头的表头行 header_row_idx = None for idx, row in temp_sheet.iterrows(): first_cell = row.iloc[0] if not pd.isna(first_cell) and str(first_cell).startswith("G/L"): header_row_idx = idx break # 从定位到的表头行读取数据 if header_row_idx is not None: final_df = excel_file.parse(sheet_name=0, header=header_row_idx) print(final_df.head()) else: print("未找到目标表头行")
处理 CSV 文件(使用 pandas)
同样先逐行扫描找到表头行位置,再读取有效数据。
import pandas as pd # 扫描 CSV 文件定位表头行 header_row_idx = None with open("your_target_file.csv", "r", encoding="utf-8") as f: for idx, line in enumerate(f): stripped_line = line.strip() if stripped_line.startswith("G/L"): header_row_idx = idx break # 读取数据 if header_row_idx is not None: final_df = pd.read_csv("your_target_file.csv", header=header_row_idx) print(final_df.head()) else: print("未找到目标表头行")
PySpark 实现方案
处理 Excel 文件
需先安装依赖包:pyspark[excel],通过临时读取无表头数据定位目标行,再读取有效内容。
from pyspark.sql import SparkSession spark = SparkSession.builder.appName("SkipIrrelevantExcelRows").getOrCreate() # 先以无表头模式读取所有行,用于扫描定位 temp_df = spark.read.format("excel").option("header", False).load("your_target_file.xlsx") header_row_idx = None # 遍历临时数据集找到表头行 for idx, row in enumerate(temp_df.collect()): first_col = row[0] if first_col is not None and str(first_col).startswith("G/L"): header_row_idx = idx break # 从目标表头行开始读取数据 if header_row_idx is not None: final_df = spark.read.format("excel")\ .option("header", True)\ .option("skipRows", header_row_idx)\ .load("your_target_file.xlsx") final_df.show() else: print("未找到目标表头行")
处理 CSV 文件
利用 PySpark 自带的 CSV 读取器,先扫描定位表头行再跳过无关内容。
from pyspark.sql import SparkSession spark = SparkSession.builder.appName("SkipIrrelevantCSVRows").getOrCreate() # 扫描 CSV 文件定位表头行 csv_rdd = spark.sparkContext.textFile("your_target_file.csv") header_row_idx = None for idx, line in enumerate(csv_rdd.collect()): if line.strip().startswith("G/L"): header_row_idx = idx break # 读取有效数据 if header_row_idx is not None: final_df = spark.read.format("csv")\ .option("header", True)\ .option("skipRows", header_row_idx)\ .load("your_target_file.csv") final_df.show() else: print("未找到目标表头行")
内容的提问来源于stack exchange,提问作者Goutham Boine
相关产品推荐
相关产品推荐

