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

如何将DataFrame中重复列(Type-I/Type-II)转换为多行结构?

实现方案

核心思路

输入表格的每行包含两组Type - I和Type - II数据,我们需要将每行拆分为两行,每行仅保留一组目标数据,后两列留空。以下用Pandas实现两种方案:

方案1:严格匹配期望行顺序

逐行拆分原数据,每组数据单独成一行,直接按原行内顺序拼接:

import pandas as pd

# 构造输入数据(实际场景可从文件/字符串读取)
input_data = [
    [560, 189, 128, 244],
    [379, 460, 357, 679],
    [238, 568, 125, 147],
    [389, 357, 780, 459]
]
df = pd.DataFrame(input_data, columns=['Type - I', 'Type - II', 'Type - I', 'Type - II'])

# 逐行拆分并构建结果列表
result_rows = []
for _, row in df.iterrows():
    # 添加当前行的第一组数据
    result_rows.append([row[0], row[1], '', ''])
    # 添加当前行的第二组数据
    result_rows.append([row[2], row[3], '', ''])

# 转换为DataFrame并输出Markdown表格
result_df = pd.DataFrame(result_rows, columns=['Type - I', 'Type - II', '', ''])
print(result_df.to_markdown(index=False))

方案2:批量拆分合并

先批量提取所有前两列和后两列数据,再合并结果,适合数据量较大的场景:

import pandas as pd

input_data = [
    [560, 189, 128, 244],
    [379, 460, 357, 679],
    [238, 568, 125, 147],
    [389, 357, 780, 459]
]
df = pd.DataFrame(input_data, columns=['Type - I', 'Type - II', 'Type - I', 'Type - II'])

# 提取前两列作为第一部分
part1 = df.iloc[:, :2].copy()
# 提取后两列并统一列名
part2 = df.iloc[:, 2:].copy()
part2.columns = part1.columns

# 合并两部分并添加空列
result_df = pd.concat([part1, part2]).reset_index(drop=True)
result_df[['', '']] = ''

# 输出Markdown表格
print(result_df.to_markdown(index=False))

输出结果

方案1的输出完全匹配你期望的结构:

Type - IType - II
560189
128244
379460
357679
238568
125147
389357
780459

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 06:01:26