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

Python基于sub_name、TH/PR及考试类型动态生成DataFrame列表头

如何根据列表中的TH、PR标识组合列表,构造存储数据的列表头?

现有代码

import pandas as pd, win32com.client as win32, fire
from colorama import Fore, init
from os.path import abspath
from timeit import default_timer as timer
def res_loop(sample="302060",
             from_seat="302061",
             to_seat="302065",
             export_file_name="excelfile"):
 
    f_no = str(sample)[0:2]
    df = pd.read_html(f"https://msbte.org.in/DISRESLIVE2021CRSLDSEP/COV6139QS21LIVEResult/SeatNumber/{f_no}/{sample}Marksheet.html")
    df_sub = df[1][0]
    #print(df)
    sub_name = [ df_sub[i] for i in range(2, len(df_sub)) if type( df_sub[i] ) == str ]
    print(sub_name)
    #print(df_sub) #Subjects Names
    df_thph=df[1][1]
    thph=[df_thph[i] for i in range(2,len(df_thph)) if type(df_thph[i])==str]
    print(thph)
    headers = []

    df_heads=df[1][2]
    #print(df_heads)
    heads=[df_heads[i] for i in range(2,len(df_heads)) if type( df_heads[i]) ==str]
    print(heads)

运行后得到的三个输出列表

sub_name=['MAN', 'PWP','MAD', 'ETI', 'NIS', 'EDP', 'CAP']
head=['TH', 'TH', 'PR', 'TH', 'PR', 'TH', 'TH', 'PR', 'PR', 'PR']
exam=['ESE', 'PA', 'ESE', 'PA', 'ESE', 'PA', 'ESE', 'PA', 'ESE', 'PA', 'ESE', 'PA', 'ESE', 'PA', 'ESE', 'PA', 'ESE', 'PA', 'ESE', 'PA']

预期输出

h1=['MAN-TH-ESE','MAN-TH-PA','PWP-TH-ESE','PWP-TH-PA','PWP-PR-ESE','PWP-PR-PA','MAD-TH-ESE','MAD-TH-PA','MAD-PR-ESE','MAD-PR-PA','ETI-TH-ESE','ETI-TH-PA','NIS-TH-ESE','NIS-TH-PA','NIS-PR-ESE','NIS-PR-PA','EDP-PR-ESE','EDP-PR-PA','CAP-PR-ESE','CAP-PR-PA']

通用实现方案

推荐直接基于pandas读取的原生表格生成,兼容性最高,完全适配科目数量、TH/PR组合变动的场景:

# 取到原始成绩表格
score_table = df[1].copy()
# 将前三行转为多级列索引,自动适配跨列产生的空值
score_table.columns = pd.MultiIndex.from_frame(score_table.iloc[0:3].T)

headers = []
# 遍历从第3列开始的所有列(前2列是公共表头不需要,可按需调整范围)
for col in score_table.columns[2:]:
    # 过滤空值后拼接三级表头
    valid_parts = [str(item) for item in col if pd.notna(item)]
    headers.append('-'.join(valid_parts))

该方案不依赖手动提取的三个列表,只要表格结构保持「第一行科目名、第二行TH/PR标识、第三行考试类型」的三级表头规则,就可以自动生成正确的列表头,不需要额外调整匹配逻辑。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:45:03