Skip to main content

Python β€” NHS Quickstart

🐍 Data wrangling · SQL Server · Dash dashboards · Automation
Why Python matters in the NHS

Python supercharges data extraction, cleaning, analytics, and automation. It plugs neatly into SQL Server, powers interactive dashboards (Dash/Plotly), and lets you productionise small services quickly.

Common NHS uses

  • Pull data from SQL Server or public datasets (CSV/Parquet/APIs).
  • Transform with pandas; model with scikit-learn.
  • Publish dashboards with Dash or scripts as small services.
  • Automate recurring reporting and validation checks.

βš™οΈ 10-minute install​

# 1) Install Python 3.11+ from python.org and tick "Add to PATH"
# 2) Create a virtual environment in your project folder
py -3.11 -m venv .venv
.\.venv\Scriptsctivate

# 3) Verify
python --version
pip --version

πŸš€ β€œHello NHS” (pandas)​

Create hello_nhs.py:

hello_nhs.py
import pandas as pd

# Fake daily admissions (3 days)
df = pd.DataFrame({
"date": pd.date_range("2025-01-01", periods=3, freq="D"),
"patients": [120, 135, 128]
})

print("Admissions summary:")
print(df.describe(include="all"))

Run:

python hello_nhs.py

πŸ”— Connect to SQL Server (safe pattern)​

Install deps:

pip install pandas sqlalchemy pyodbc python-dotenv

Add .env (do not commit this file):

.env
SQLSERVER_SERVER=YOURSERVER
SQLSERVER_DATABASE=NHS_Analytics

Create query_sqlserver.py:

query_sqlserver.py
import os, urllib.parse, pandas as pd
from sqlalchemy import create_engine, text
from dotenv import load_dotenv

load_dotenv()

params = urllib.parse.quote_plus(
"DRIVER={ODBC Driver 18 for SQL Server};"
f"SERVER={os.getenv('SQLSERVER_SERVER')};"
f"DATABASE={os.getenv('SQLSERVER_DATABASE')};"
"Trusted_Connection=Yes;Encrypt=Yes;"
)
engine = create_engine(f"mssql+pyodbc:///?odbc_connect={params}")

sql = text("""
SELECT TOP (100)
practice_id, total_appointments, attendance_rate
FROM dbo.vw_PracticeKPI
ORDER BY total_appointments DESC
""")
df = pd.read_sql(sql, engine)
print(df.head())

Run:

python query_sqlserver.py

πŸ“Š First chart (Plotly Express)​

pip install plotly

Create chart.py:

chart.py
import pandas as pd, plotly.express as px

df = pd.DataFrame({
"practice_id": ["A","B","C"],
"appointments": [140,120,95]
})
fig = px.bar(df, x="practice_id", y="appointments",
title="Appointments by Practice")
fig.show()

πŸ§ͺ Optional: tiny Dash dashboard (15 min)​

pip install dash

Create app.py:

app.py
import dash
from dash import html, dcc
import plotly.express as px, pandas as pd

df = pd.DataFrame({
"practice_id": ["A","B","C"],
"appointments": [140,120,95]
})
fig = px.bar(df, x="practice_id", y="appointments", title="Appointments by Practice")

app = dash.Dash(__name__); app.title = "NHS KPI (Demo)"
app.layout = html.Div([html.H2("NHS KPI Dashboard"), dcc.Graph(figure=fig)])

if __name__ == "__main__":
app.run_server(debug=True)

Run and open http://127.0.0.1:8050


🧰 NHS-ready packages​

PackageUse case
pandasdata cleaning & aggregation
plotly / matplotlibcharts & exploratory viz
sqlalchemy + pyodbcconnect to SQL Server
python-dotenvload secrets from .env (local only)
dashinteractive dashboards
openpyxlExcel automation (read/write)
pyarrowfast Parquet/Arrow IO

πŸ–₯ IDE setup (VS Code)​

  1. Install VS Code.
  2. Add extensions: Python (Microsoft), Jupyter, Pylance.
  3. Enable the interpreter from your project’s .venv.
  4. Turn on Format on Save and add a linter/formatter (e.g., ruff, black).

Optional requirements.txt:

requirements.txt
pandas
sqlalchemy
pyodbc
python-dotenv
plotly
dash

Install with:

pip install -r requirements.txt

πŸ”’ IG & safety checklist​

  • Use synthetic/de-identified data in examples.
  • Keep secrets out of code; load from env vars; rotate in production via a secret store.
  • Avoid free-text PHI in logs/notebooks; aggregate before export; apply small-number suppression.
  • Document sources, owners, and update cadence in the repo README.

πŸ“ Measuring impact​

  • Velocity: time from data pull β†’ first chart.
  • Reliability: % successful script runs / dashboard refreshes.
  • Quality: validation checks; peer review via PRs.
  • Reusability: runs from a clean clone without manual tweaks.

πŸ”— See also​

See also: SQL Server Β· Dash Β· VS Code Β· Git Β· GitHub Β· Docker Β· Secrets & .env

What’s next?

You’ve completed the Learn β€” Python stage. Keep momentum: