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

如何跳过部分列表头创建DataFrame并转换为多级列格式

问题解答

问题1:如何在创建DataFrame时跳过部分列表头?

根据数据来源不同,有两种常见处理方式:

  • 从CSV文件创建:使用pandas.read_csv()的skiprows参数跳过指定行,或header参数指定表头行:
    • 跳过前2行(含无效表头):pd.read_csv('file.csv', skiprows=2)
    • 指定第3行(索引为2)作为表头:pd.read_csv('file.csv', header=2)
  • 从列表数据创建:直接切片跳过无效表头,再指定有效表头:
    import pandas as pd
    data = [['无效表头1', '无效表头2'], ['有效列名1', '有效列名2'], ['值1', '值2'], ['值3', '值4']]
    df = pd.DataFrame(data[2:], columns=data[1])
    

问题2:DataFrame格式重塑

原始数据

Candidate Name    Subject    Keyword  Count
   User1         optional    devops      1
   User1         mandatory      aws      0
   User1         mandatory      ec2      1
   User1         optional    python      1
   User1         optional      java      1
   User1         mandatory   dotnet      0
   User2         optional    devops      1
   User2         mandatory      aws      1
   User2         mandatory      ec2      0
   User3         optional    devops      1
   User3         mandatory      ec2      1
   User3         mandatory      aws      0
   User3         optional      java      1

目标格式

生成以Candidate Name为行索引,Subject为上层列索引、Keyword为下层列索引的多层列DataFrame。

修正后的实现代码

import pandas as pd

# 读取CSV数据
df = pd.read_csv('Sample.csv')

# 用pivot_table重塑数据,自动填充缺失值为0
pivoted_df = df.pivot_table(
    index='Candidate Name',
    columns=['Subject', 'Keyword'],
    values='Count',
    fill_value=0,
    aggfunc='sum'
)

# 定义列顺序:先mandatory后optional,各Subject下的Keyword按字母排序
subject_order = ['mandatory', 'optional']
sorted_columns = []
for subject in subject_order:
    # 对当前Subject下的Keyword排序
    sorted_keywords = sorted(pivoted_df[subject].columns)
    sorted_columns.extend([(subject, kw) for kw in sorted_keywords])

# 重新排列列
pivoted_df = pivoted_df[sorted_columns]

# 如果需要将Count转换为存在标记(比如原Count为0/1都显示1,仅缺失显示0),可取消下面注释
# pivoted_df = pivoted_df.applymap(lambda x: 1 if x != -1 else 0)  # 根据实际需求调整判断逻辑

print(pivoted_df)

代码说明

  1. pivot_table相比pivot更稳定,能处理重复的Candidate Name+Subject+Keyword组合,并用fill_value补全缺失值。
  2. 通过自定义列顺序,确保输出符合mandatory在前、optional在后的要求,同时对Keyword按字母排序。
  3. 若需转换Count为存在/不存在的标记,可通过applymap调整值的映射逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:10:24