数据分析报告模板

Python数据分析入门Python

问题

如何用模板自动生成数据分析报告?

答题要点

from jinja2 import Template
import pandas as pd
from datetime import datetime

# HTML报告模板
report_template = """
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        h1 { color: #333; }
        table { border-collapse: collapse; width: 100%; margin: 20px 0; }
        th, td { border: 1px solid #ddd; padding: 12px; text-align: left; }
        th { background-color: #4472C4; color: white; }
        tr:nth-child(even) { background-color: #f2f2f2; }
        .metric { display: inline-block; margin: 20px; padding: 20px;
                  background: #f0f0f0; border-radius: 5px; }
        .metric-value { font-size: 32px; font-weight: bold; color: #4472C4; }
    </style>
</head>
<body>
    <h1>{{ title }}</h1>
    <p>报告日期: {{ report_date }}</p>

    <h2>核心指标</h2>
    {% for metric in metrics %}
    <div class="metric">
        <div>{{ metric.name }}</div>
        <div class="metric-value">{{ metric.value }}</div>
        <div style="color: {{ 'green' if metric.change > 0 else 'red' }}">
            {{ metric.change }}%
        </div>
    </div>
    {% endfor %}

    <h2>详细数据</h2>
    {{ table_html | safe }}

    <h2>趋势图</h2>
    <img src="{{ chart_path }}" style="max-width: 100%;">

    <h2>分析结论</h2>
    <ul>
    {% for insight in insights %}
        <li>{{ insight }}</li>
    {% endfor %}
    </ul>
</body>
</html>
"""

# 准备数据
df = pd.read_csv('daily_data.csv')

metrics = [
    {'name': 'DAU', 'value': '150,000', 'change': 5.2},
    {'name': 'GMV', 'value': '¥520万', 'change': -2.1},
    {'name': '新增用户', 'value': '5,000', 'change': 10.5}
]

# 生成表格HTML
table_html = df.head(10).to_html(index=False, classes='data-table')

insights = [
    'DAU环比增长5.2%,主要来自微信渠道',
    'GMV略有下降,需关注转化率',
    '新增用户表现良好,继续加大投放'
]

# 渲染模板
template = Template(report_template)
html_content = template.render(
    title='运营日报 - 2024-12-01',
    report_date=datetime.now().strftime('%Y-%m-%d %H:%M'),
    metrics=metrics,
    table_html=table_html,
    chart_path='trend_chart.png',
    insights=insights
)

# 保存HTML
with open('report.html', 'w', encoding='utf-8') as f:
    f.write(html_content)

# Markdown报告模板
md_template = """
# {{ title }}

**报告日期**: {{ report_date }}

## 核心指标

| 指标 | 数值 | 变化 |
|------|------|------|
{% for m in metrics -%}
| {{ m.name }} | {{ m.value }} | {{ m.change }}% |
{% endfor %}

## 详细数据

{{ table_md }}

## 分析结论

{% for insight in insights -%}
- {{ insight }}
{% endfor %}
"""

# 渲染Markdown
md_template_obj = Template(md_template)
md_content = md_template_obj.render(
    title='运营周报',
    report_date=datetime.now().strftime('%Y-%m-%d'),
    metrics=metrics,
    table_md=df.to_markdown(index=False),
    insights=insights
)

with open('report.md', 'w', encoding='utf-8') as f:
    f.write(md_content)

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题