Tags:

Here’s a simple guide on running Jupyter Notebooks and generating HTML reports using Python scripts. We’ll use the popular nbconvert tool for converting Jupyter Notebooks into HTML reports. We’ll also demonstrate using a dataset, such as the Iris dataset from the sklearn library.


Step 1: Install Required Libraries

Make sure you have Jupyter and necessary libraries installed. You can install them with:

pip install notebook nbconvert pandas scikit-learn

Step 2: Create a Jupyter Notebook

Create a simple Jupyter Notebook (e.g., iris_analysis.ipynb) with the following content:

# Import necessary libraries
import pandas as pd
from sklearn.datasets import load_iris

# Load the Iris dataset
iris = load_iris()
data = pd.DataFrame(data=iris.data, columns=iris.feature_names)
data['target'] = iris.target

# Display the first few rows
print("First 5 rows of the dataset:")
display(data.head())

# Generate summary statistics
print("Summary statistics:")
display(data.describe())

# Visualize the data
import matplotlib.pyplot as plt
plt.figure(figsize=(6, 4))
plt.scatter(data['sepal length (cm)'], data['sepal width (cm)'], c=data['target'], cmap='viridis')
plt.title("Sepal Length vs Sepal Width")
plt.xlabel("Sepal Length (cm)")
plt.ylabel("Sepal Width (cm)")
plt.colorbar(label='Target')
plt.show()

Save this notebook.


Step 3: Convert the Notebook to HTML

To convert the notebook to an HTML report using a Python script, use the nbconvert module.

Create a Python script (e.g., convert_to_html.py) with the following code:

import nbformat
from nbconvert import HTMLExporter

# Define the notebook file and output HTML file
notebook_file = 'iris_analysis.ipynb'
output_html_file = 'iris_analysis.html'

# Read the notebook
with open(notebook_file, 'r', encoding='utf-8') as f:
    notebook_content = nbformat.read(f, as_version=4)

# Convert the notebook to HTML
html_exporter = HTMLExporter()
html_content, _ = html_exporter.from_notebook_node(notebook_content)

# Write the HTML content to a file
with open(output_html_file, 'w', encoding='utf-8') as f:
    f.write(html_content)

print(f"Notebook successfully converted to {output_html_file}")

Run the script:

python convert_to_html.py

Step 4: View the HTML Report

After running the script, you’ll find the file iris_analysis.html in the current directory. Open it in any web browser to view the report.


Notes

  • This method keeps your workflow automated and integrates well into larger pipelines.
  • For further customization, consider using templates with nbconvert.
  • To execute the notebook programmatically before conversion, you can use the ExecutePreprocessor from the nbconvert library.