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

提取列表中的DataFrame并生成PDF输出的技术实现问询

Got it, let's walk through how to turn your list of profession-specific DataFrames into a nicely formatted PDF. Here are two solid Python-based approaches—one for full customization, another for quick results:


Approach 1: ReportLab (Professional, Customizable Layout)

This method gives you complete control over styling (headers, colors, borders, etc.) for a polished PDF.

Step 1: Install Required Packages

First, install the tools you'll need:

pip install pandas reportlab

Step 2: Full Code Example

Assuming your list Y is structured as tuples of (profession_name, dataframe) (if not, see the note at the end to adapt it):

import pandas as pd
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.lib.styles import getSampleStyleSheet

# Example list Y (replace with your actual data)
Y = [
    ("Profession1", pd.DataFrame({
        "Searchterm": ["internist", "pneumo news", "der urologe"],
        "Product": ["Der Internist", "Pneumo News", "Der Urologe"],
        "Quantity": [3, 1, 5]
    })),
    ("Profession2", pd.DataFrame({
        "Searchterm": ["der nervenarzt", "der kardiologe", ".piefel", "therapiedes zenker"],
        "Product": ["Der Internist", "Der Kardiologe", "Strahlentherapie", "Pathophysiologie"],
        "Quantity": [7, 2, 6, 1]
    }))
]

def generate_profession_pdf(data_list, output_path="professions_report.pdf"):
    # Set up the PDF document
    doc = SimpleDocTemplate(output_path, pagesize=letter)
    elements = []
    styles = getSampleStyleSheet()
    
    for profession_name, df in data_list:
        # Add a bold heading for the profession
        heading = Paragraph(f"<b>{profession_name}</b>", styles["Heading1"])
        elements.append(heading)
        
        # Convert DataFrame to a list of lists (includes column headers)
        table_data = [df.columns.tolist()] + df.values.tolist()
        
        # Create the table and apply styling
        table = Table(table_data)
        style = TableStyle([
            ('BACKGROUND', (0,0), (-1,0), colors.darkgray),
            ('TEXTCOLOR', (0,0), (-1,0), colors.whitesmoke),
            ('ALIGN', (0,0), (-1,-1), 'LEFT'),
            ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
            ('FONTSIZE', (0,0), (-1,0), 12),
            ('BOTTOMPADDING', (0,0), (-1,0), 12),
            ('BACKGROUND', (0,1), (-1,-1), colors.lightblue),
            ('GRID', (0,0), (-1,-1), 1, colors.black)
        ])
        table.setStyle(style)
        
        # Add the table and a space before the next profession
        elements.append(table)
        elements.append(Paragraph("<br/>", styles["Normal"]))
    
    # Build and save the PDF
    doc.build(elements)

# Generate your PDF
generate_profession_pdf(Y)

Key Customizations You Can Make:

  • Adjust column widths by adding colWidths=[250, 250, 80] to the Table() constructor (tweak numbers for your content)
  • Change colors, fonts, or padding by modifying the TableStyle rules
  • Add page numbers, footers, or logos by extending the elements list with additional ReportLab components

Approach 2: Matplotlib (Quick, Minimal Setup)

If you don't need fancy styling and just want a straightforward PDF of tables, this method is faster.

Step 1: Install Required Packages

pip install pandas matplotlib

Step 2: Full Code Example

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

# Using the same example Y list as before
Y = [
    ("Profession1", pd.DataFrame({...})),
    ("Profession2", pd.DataFrame({...}))
]

def quick_pdf_from_dataframes(data_list, output_path="quick_professions_report.pdf"):
    with PdfPages(output_path) as pdf:
        for profession_name, df in data_list:
            # Create a letter-sized figure
            fig, ax = plt.subplots(figsize=(8.5, 11))
            ax.axis('off')  # Hide unnecessary axes
            
            # Add profession title
            plt.title(f"{profession_name}", fontsize=14, fontweight='bold', pad=20)
            
            # Generate the table from the DataFrame
            table = ax.table(
                cellText=df.values,
                colLabels=df.columns,
                loc='center',
                cellLoc='left'
            )
            
            # Adjust table appearance
            table.auto_set_font_size(False)
            table.set_fontsize(10)
            table.scale(1.2, 1.2)  # Make text easier to read
            
            # Fix layout to prevent content from being cut off
            plt.tight_layout()
            
            # Add this page to the PDF
            pdf.savefig(fig)
            plt.close()

# Generate your PDF
quick_pdf_from_dataframes(Y)

Important Note for Your List Y

If your list only contains DataFrames (not tuples with profession names), make sure each DataFrame has a name attribute set (e.g., df.name = "Profession1"). Then modify the loops in either code example to use for df in data_list: profession_name = df.name instead of the tuple unpacking.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:45:15