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

如何用Python程序化创建Excel样式报表表格并实现多表并排?

解决方案

实现步骤

  1. 数据分组:按餐厅名称对DataFrame进行分组,确保每个餐厅的数据独立处理。
  2. 排序与排名:对每个餐厅的员工数据按分数升序排序(匹配你示例中的排名逻辑),并生成从1开始的排名。
  3. 生成表格:为每个餐厅创建PrettyTable,设置标题和列名,填充排序后的员工数据。
  4. 并排展示:将每个表格的字符串内容按行拆分,逐行拼接多个表格的对应行,实现并排显示。

完整代码

import pandas as pd
from prettytable import PrettyTable

# 初始化示例数据(包含多餐厅演示)
df = pd.DataFrame()
df["name"] = ["Nick","Bob", "George", "Jason","Death"]
df["Restaurant Manager"] = ["Sam","Mason", "Sam", "Mason","Mason"]
df["Score"] = [1,5, 7, 2,10]
df['Percentile Rank'] = [0,50,80,20,100]
df["Restaurant Name"] = "Elise"

# 添加第二家餐厅数据用于演示并排效果
df2 = df.copy()
df2["Restaurant Name"] = "Anna's Bistro"
df = pd.concat([df, df2], ignore_index=True)

# 存储每个餐厅的表格行数据
restaurant_table_lines = []

# 遍历每个餐厅分组
for restaurant_name, group in df.groupby('Restaurant Name'):
    # 按分数升序排序,生成排名(从1开始)
    sorted_group = group.sort_values('Score', ascending=True).reset_index(drop=True)
    sorted_group['Rank'] = sorted_group.index + 1
    
    # 创建PrettyTable实例
    table = PrettyTable()
    table.title = restaurant_name
    table.field_names = ["Rank", "Employee Name", "Score", "Percentile"]
    
    # 填充表格数据
    for _, row in sorted_group.iterrows():
        table.add_row([row['Rank'], row['name'], row['Score'], row['Percentile Rank']])
    
    # 将表格转为字符串并按行拆分,存入列表
    restaurant_table_lines.append(table.get_string().split('\n'))

# 计算最长表格的行数,确保所有表格对齐
max_line_count = max(len(lines) for lines in restaurant_table_lines)

# 逐行拼接并打印所有表格
for line_idx in range(max_line_count):
    current_line_parts = []
    for lines in restaurant_table_lines:
        # 若当前行存在则取该行,否则补对应长度的空格
        if line_idx < len(lines):
            current_line_parts.append(lines[line_idx])
        else:
            current_line_parts.append(' ' * len(lines[0]))
    # 用空格分隔多个表格的行
    print('    '.join(current_line_parts))

代码说明

  • 多餐厅支持:通过groupby('Restaurant Name')自动处理任意数量的餐厅。
  • 排名逻辑:按分数升序排序后生成排名,完全匹配你示例中的Nick(Rank1)、George(Rank2)的顺序。
  • 并排展示:将每个表格拆分为行列表,逐行拼接不同表格的对应行,确保表格横向对齐。
  • 扩展性:如果需要按餐厅经理拆分表格,只需将groupby('Restaurant Name')改为groupby(['Restaurant Name', 'Restaurant Manager']),并调整表格标题即可。

内容的提问来源于stack exchange,提问作者Gaetano Dona-Jehan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 10:20:23