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

如何在Pandas中重新定位表格元素并调整布局

Pandas 表格结构重排解决方案

原始表格

Type LabelInitial20222023Difference
APPSA/B/C50046931
BACSB/C/D532
CAPSC/D/E1055

目标表格

Type Label/Initial20222023Difference
APPS50046931
A
B
C
BACS532
B
C
D
CAPS1055
C
D
E

实现代码

import pandas as pd

# 读取或构造原始数据(这里直接构造示例数据)
df = pd.DataFrame({
    'Type Label': ['APPS', 'BACS', 'CAPS'],
    'Initial': ['A/B/C', 'B/C/D', 'C/D/E'],
    '2022': [500, 5, 10],
    '2023': [469, 3, 5],
    'Difference': [31, 2, 5]
})

# 初始化存储结果的列表
result_rows = []

# 遍历原始表格每一行,拆分重组内容
for _, row in df.iterrows():
    # 添加带加粗格式的Type Label行
    result_rows.append({
        'Type Label/Initial': f"**{row['Type Label']}**",
        '2022': row['2022'],
        '2023': row['2023'],
        'Difference': row['Difference']
    })
    # 拆分Initial列的元素,逐个添加空数值行
    for item in row['Initial'].split('/'):
        result_rows.append({
            'Type Label/Initial': item,
            '2022': None,
            '2023': None,
            'Difference': None
        })

# 转换为最终DataFrame
result_df = pd.DataFrame(result_rows)

# 输出Markdown格式表格(若需导出可直接使用该结果)
print(result_df.to_markdown(index=False))

代码说明

  1. 先构造或读取原始数据,确保Initial列是用/分隔的字符串格式。
  2. 遍历每行数据,优先添加包含加粗Type Label和对应数值的记录。
  3. 拆分Initial列的字符串,为每个元素生成一行仅含标签、数值为空的记录。
  4. 将所有记录整合成新的DataFrame,通过to_markdown输出符合要求的表格格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:33:27