You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pandas处理CSV文件时无法正确提取标题、列名及数据

从带分层标题的CSV提取内容的问题修复

问题背景

你的CSV文件包含带编号的分层标题行、重复的列名行和对应数据行,需要提取标题文本(如Top Header、Next Level)、列名及对应分组数据,但原Pandas代码无法正确读取第一行,且提取逻辑不符合预期。

CSV文件内容

1.1.1.Top Header

Attribute,Field Description,Table,Column, Filter

Quarter,Fiscal Current Quarter,tableA,col1,A=B

Blah, Blah, Blah, Blah, Blah

Blah, Blah, Blah, Blah, Blah

Blah, Blah, Blah, Blah, Blah

1.1.2.Next Level

Attribute,Field Description,Table,Column, Filter

Blah, Blah, Blah, Blah, Blah

原代码

import pandas as pd

# Load the CSV file
df = pd.read_csv('dd.csv')

# Fill NaN values with "NA"
df = df.fillna("NA")

# Find the row indexes of the header rows
header_indexes = df[df.iloc[:,0].str.match(r'^(\d+\.)+\d+\..*')].index.tolist()

# Check if there are any headers and data rows
if header_indexes and header_indexes[-1] < len(df) - 1:
    # Extract header names and remove the numeric values
    header_names = [df.iloc[i,0].split('.')[1:] for i in header_indexes]
    header_names = [', '.join([h.strip() for h in header]) for header in header_names]
    
    # Extract the column names
    column_names = df.iloc[header_indexes[-1]+1,:].tolist()
    
    print("Header Names:", header_names)
    print("Column Names:", column_names)
else:
    print("No headers or data rows found in the CSV file.")

问题原因

  1. 表头识别错误:pd.read_csv()默认将第一行作为DataFrame表头,导致实际的标题行1.1.1.Top Header被当作表头,后续所有行的解析完全错位。
  2. 标题提取逻辑错误:原代码用split('.')[1:]处理标题行,会残留编号部分(如1.1.1.Top Header拆分后取[1:]得到['1','1','Top Header']),无法正确提取纯标题文本。
  3. 空行处理不当:CSV中的空行被解析为全NaN行,干扰行匹配逻辑。

修复后的代码

import pandas as pd

# 1. 读取所有行,过滤空行,保留原始结构
with open('dd.csv', 'r') as f:
    lines = [line.strip() for line in f if line.strip()]

# 2. 识别标题、列名和数据行,分组整理
header_pattern = r'^(\d+\.)+\d+\..*'
headers = []
data_groups = []
current_group = []
col_names = None

for line in lines:
    # 匹配标题行
    if pd.Series([line]).str.match(header_pattern)[0]:
        # 保存上一组数据(如果存在)
        if current_group and col_names:
            data_groups.append((headers[-1], pd.DataFrame(current_group, columns=col_names)))
        # 提取纯标题文本:取编号后的最后一段
        header_text = line.split('.')[-1].strip()
        headers.append(header_text)
        current_group = []
        col_names = None
    # 匹配列名行(通过关键字识别,可根据实际调整)
    elif 'Attribute' in line:
        col_names = [col.strip() for col in line.split(',')]
    # 处理数据行
    else:
        if col_names:
            current_group.append([val.strip() for val in line.split(',')])

# 保存最后一组数据
if current_group and col_names:
    data_groups.append((headers[-1], pd.DataFrame(current_group, columns=col_names)))

# 3. 输出结果
print("提取的标题列表:", headers)
print("\n各分组数据:")
for header, df in data_groups:
    print(f"\n=== {header} ===")
    print(df)

代码说明

  1. 原始行读取:直接读取文件并过滤空行,避免Pandas自动解析表头导致的错位问题。
  2. 标题提取优化:通过split('.')[-1]直接获取编号后的纯标题文本,无需处理多余的编号部分。
  3. 数据分组整理:遍历行时自动识别标题、列名和对应数据,将每个标题下的数据整理为独立的DataFrame,方便后续使用。

内容的提问来源于stack exchange,提问作者paddu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 09:20:40