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

如何在Pandas中实现单元格跨多列合并(水果类别分组场景)

实现DataFrame类别跨列合并并移除原列

场景说明

你的DataFrame结构中,Fruit Type列的类别行(如Berries、Citrus)对应的Fruit1-Fruit4列均为空,下方两行是该类别的具体水果。要实现类似Excel的跨列合并显示,再移除Fruit Type列,可分两种场景处理:


场景1:仅在Jupyter/Notebook中视觉显示合并效果

如果只是需要在Notebook里展示时呈现跨列合并的视觉效果,用pandas的Styler通过CSS样式模拟:

import pandas as pd

# 示例DataFrame(替换成你的实际数据)
data = {
    'Fruit Type': ['Berries', None, None, 'Citrus', None, 'Melons', None],
    'Fruit1': [None, 'Strawberry', 'Blackberry', None, 'Orange', None, 'Watermelon'],
    'Fruit2': [None, 'Blueberry', None, None, 'Lemon', None, 'Cantaloupe'],
    'Fruit3': [None, 'Raspberry', None, None, 'Lime', None, None],
    'Fruit4': [None, None, None, None, 'Grapefruit', None, None]
}
df = pd.DataFrame(data)

def style_merge_cells(df):
    # 筛选出需要合并的类别行索引
    merge_row_indices = df[df['Fruit Type'].notna()].index
    table_styles = []
    
    # 为每个类别行设置样式:隐藏Fruit Type列,将类别文本跨列显示
    for idx in merge_row_indices:
        # 隐藏当前行的Fruit Type单元格
        table_styles.append({
            'selector': f'tbody tr:nth-child({idx+1}) td:first-child',
            'props': [('display', 'none')]
        })
        # 将类别文本放到Fruit1列,设置加粗居中,覆盖整行的Fruit列区域
        table_styles.append({
            'selector': f'tbody tr:nth-child({idx+1}) td:nth-child(2)',
            'props': [
                ('content', f'"{df.loc[idx, "Fruit Type"]}"'),
                ('font-weight', 'bold'),
                ('text-align', 'center'),
                ('padding', '8px')
            ]
        })
        # 为当前行的Fruit1-Fruit4列设置统一边框,模拟合并视觉
        table_styles.append({
            'selector': f'tbody tr:nth-child({idx+1}) td:nth-child(n+2)',
            'props': [('border', '1px solid #ddd')]
        })
    
    # 隐藏Fruit Type列的表头
    table_styles.append({
        'selector': 'th:first-child',
        'props': [('display', 'none')]
    })
    
    return df.style.set_table_styles(table_styles)

# 应用样式并显示
styled_df = style_merge_cells(df)
styled_df

场景2:导出到Excel实现真正的合并单元格

如果需要生成Excel文件并保留合并单元格的结构,用openpyxl操作:

import pandas as pd
from openpyxl import load_workbook

# 保存原始数据到Excel
df.to_excel('fruit_list.xlsx', index=False, engine='openpyxl')

# 加载工作簿进行合并操作
wb = load_workbook('fruit_list.xlsx')
ws = wb.active

# 获取需要合并的类别行(转换为Excel行号,表头占第1行,数据从第2行开始)
merge_rows = [row+2 for row in df[df['Fruit Type'].notna()].index]

for row_num in merge_rows:
    # 合并当前行的Fruit1到Fruit4列(对应Excel的B到E列)
    ws.merge_cells(start_row=row_num, start_column=2, end_row=row_num, end_column=5)
    # 将类别名称填入合并后的单元格
    ws.cell(row=row_num, column=2).value = df.loc[row_num-2, 'Fruit Type']

# 删除Fruit Type列(Excel的A列)
ws.delete_cols(1)

# 保存修改后的文件
wb.save('fruit_list_merged.xlsx')

两种方法分别对应可视化展示和实际文件生成的需求,根据你的使用场景选择即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 05:50:27