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

Python定制SAS风格数据透视表:格式美化与问题修正

问题描述

原本使用SAS创建了一份数据透视表,希望在Python中实现具有近乎相同字体、颜色的版本。编写代码生成基础透视表后,存在以下问题需要解决:

  1. 年份显示为浮点数(如2024.0而非2024),尝试转换类型无效;
  2. 表头自动添加了'country'字段,调整后仍未解决;
  3. 需要优化透视表的线条、颜色、字体和尺寸以提升美观度。
    原始代码如下:
filtered_table=mytable[mytable['country'] != "Japan"]

def t_design(a):
 pvt_table = pd.pivot_table(filtered_table, index=[a], columns= ['years'], aggfunc='count', fill_value=0)
 pvt_table.loc['Total'].pvt_table.sum()
 html_file=pvt_table.to_html()
 title= f"<h1>My table Title for {a} </h1>"
 html_file= title + html_file
 with open(f'my file direction/{a}.html','w')  as f:
  f.write(html_file)

t_design('job_code')
t_design('city_code')
解决方案

1. 修复年份显示为浮点数的问题

原因

years字段可能为浮点类型,或透视表生成时列名被自动转换为浮点。

处理步骤

  • 先转换原始数据的years字段为整数:
    filtered_table['years'] = filtered_table['years'].astype(int)
    
  • 若原始数据存在缺失值,先填充再转换:
    filtered_table['years'] = filtered_table['years'].fillna(0).astype(int)
    
  • 若透视表生成后列名仍为浮点,手动修改列名:
    pvt_table.columns = pvt_table.columns.get_level_values(1).astype(int)
    

2. 移除表头多余的'country'字段

原因

使用count聚合函数时,pandas会统计所有非分组/列字段,导致表头出现多层索引(包含country)。

处理步骤

  • 方法1:指定统计字段
    在pivot_table中明确指定要统计的字段,避免聚合所有字段,再移除多层表头的顶层:
    pvt_table = pd.pivot_table(filtered_table, index=[a], columns=['years'], values=[a], 
                               aggfunc='count', fill_value=0)
    pvt_table = pvt_table.droplevel(0, axis=1)
    
  • 方法2:用groupby替代
    更直接的方式生成透视表,避免多层索引:
    pvt_table = filtered_table.groupby([a, 'years']).size().unstack(fill_value=0)
    

3. 美化表格(字体、颜色、线条、尺寸)

通过嵌入自定义CSS样式,实现和SAS表格接近的视觉效果,以下是修改后的完整代码:

import pandas as pd

filtered_table = mytable[mytable['country'] != "Japan"]
# 预处理年份为整数
filtered_table['years'] = filtered_table['years'].astype(int)

def t_design(a):
    # 生成透视表并清理表头
    pvt_table = pd.pivot_table(filtered_table, index=[a], columns=['years'], values=[a], 
                               aggfunc='count', fill_value=0)
    pvt_table = pvt_table.droplevel(0, axis=1)
    
    # 添加总计行
    pvt_table.loc['Total'] = pvt_table.sum(axis=0)
    
    # 自定义CSS样式(可根据SAS表格调整)
    custom_css = """
    <style>
        body { font-family: Arial, sans-serif; }
        h1 { color: #2c3e50; margin: 20px 0; }
        table { 
            width: 80%; 
            border-collapse: collapse; 
            font-size: 14px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        th, td { 
            padding: 12px 15px; 
            text-align: center;
            border: 1px solid #ddd;
        }
        th { 
            background-color: #3498db; 
            color: white;
            font-weight: bold;
        }
        tr:nth-child(even) { background-color: #f8f9fa; }
        tr:hover { background-color: #eaf2f8; }
        .total-row { 
            background-color: #2c3e50 !important; 
            color: white;
            font-weight: bold;
        }
    </style>
    """
    
    # 生成带样式的HTML表格
    html_table = pvt_table.to_html()
    # 给总计行添加样式类
    html_table = html_table.replace('<tr><th>Total</th>', '<tr class="total-row"><th>Total</th>')
    
    # 组合完整HTML内容
    html_content = custom_css + f"<h1>My table Title for {a}</h1>" + html_table
    
    # 保存文件(注意替换为有效路径)
    with open(f'my file direction/{a}.html', 'w', encoding='utf-8') as f:
        f.write(html_content)

t_design('job_code')
t_design('city_code')

样式调整说明

  • 可修改font-family替换为SAS使用的字体(如"Times New Roman");
  • 调整background-color、color的值匹配SAS表格的配色;
  • 修改width、padding等参数调整表格尺寸和单元格间距。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 17:37:22