Medical AI · Foundations · Lesson 5 of 6
Setting up Python and Colab for clinical data work
Reviewed by Dr. Ram Kumar G, MBBS, MD (Internal Medicine), MPH (USA), on · Last updated
- Beginner
- Technical focus
- About 30 minutes
- Includes exercise
In short
You can start with Python for healthcare data in Google Colab, which runs notebooks in the browser with no installation, or with a local Python environment when you need more control. Either way, the core tools are pandas for tables, scikit-learn for models and matplotlib for charts. Use only synthetic or properly licensed data while learning, and keep work reproducible with fixed versions, random seeds and 'restart and run all'.
You will learn to
- Open and run a notebook in Google Colab, or set up a local Python environment
- Load a table with pandas, summarise it and find missing values
- Make a simple chart with matplotlib
- Apply basic habits for safe, reproducible work with clinical data
Two ways to run Python
A notebook mixes code, results and notes in one document, which makes it a good way to learn and to explain an analysis. You can run notebooks in the cloud or on your own computer.
| Google Colab | Local environment | |
|---|---|---|
| Setup | None: open a notebook in the browser with a Google account | Install Python, create an environment, install packages |
| Cost | Free tier with usage limits; paid tiers available | Free; uses your own computer |
| Files | Temporary: files are lost when the session ends unless saved to Drive or downloaded | Stay on your disk |
| Data protection | Data goes to a third-party cloud service; do not upload identifiable patient data to a personal account | Data stays on your machine, subject to your organisation's policies |
| Best for | Learning, this course's exercises, quick experiments | Longer projects, version control, approved work environments |
Option 1: Google Colab
Each exercise in this course will have an 'Open in Colab' link. Colab already includes numpy, pandas, scikit-learn and matplotlib. Run a cell with Shift+Enter, and use Runtime → Restart and run all to check that the whole notebook works from the top.
The first cell below checks which versions are installed. Your output will differ from anyone else's, which is exactly why recording versions matters.
import sys
import numpy as np
import pandas as pd
import sklearn
print(f"Python {sys.version.split()[0]}")
for lib in (np, pd, sklearn):
print(f"{lib.__name__:<8} {lib.__version__}")Option 2: a local environment
Install a currently supported version of Python 3 from python.org (3.11 or newer as of 2026). Then create a separate environment for each project, so the packages for one project do not break another.
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install numpy pandas scikit-learn matplotlib jupyter
pip freeze > requirements.txt # record exact versions
jupyter notebook # opens notebooks in your browser- Package managers such as conda or uv are common alternatives; check licence terms for your organisation before choosing one.
- requirements.txt lets someone else recreate your environment with pip install -r requirements.txt.
Loading and summarising a table
pandas reads tables from CSV files, spreadsheets and databases into a DataFrame. The example uses a small synthetic table written into the code, so it runs anywhere.
from io import StringIO
import pandas as pd
csv_text = """patient_id,age,sex,hba1c,systolic_bp
s01,54,F,7.9,138
s02,61,M,6.4,142
s03,47,F,8.6,129
s04,70,M,,151
s05,58,F,6.9,134
s06,66,M,9.1,147
"""
df = pd.read_csv(StringIO(csv_text)) # with a real file: pd.read_csv("labs.csv")
print(df.shape)
print(df.describe().round(1))
print("\nMissing values:\n", df.isna().sum())
# (6, 5)
# age hba1c systolic_bp
# count 6.0 5.0 6.0
# mean 59.3 7.8 140.2
# std 8.3 1.1 8.2
# min 47.0 6.4 129.0
# 25% 55.0 6.9 135.0
# 50% 59.5 7.9 140.0
# 75% 64.8 8.6 145.8
# max 70.0 9.1 151.0
#
# Missing values:
# patient_id 0
# age 0
# sex 0
# hba1c 1
# systolic_bp 0- describe() quietly skips missing values: the HbA1c count is 5, not 6. Always check counts before trusting a mean.
A first chart
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(5, 3.5))
ax.scatter(df.age, df.hba1c)
ax.axhline(7.0, linestyle="--", linewidth=1)
ax.set_xlabel("Age (years)")
ax.set_ylabel("HbA1c (%)")
ax.set_title("Synthetic patients: HbA1c by age")
fig.tight_layout()
fig.savefig("hba1c_by_age.png", dpi=150)- matplotlib leaves out points with missing values, so the chart shows five patients, not six. Mention this in any caption.
Habits for safe, reproducible work
- Use synthetic or properly licensed open data while learning. Never copy data from clinical systems into personal notebooks, cloud drives or AI tools.
- Keep data, passwords and API keys out of code and out of version control (list data folders in .gitignore; read keys from environment variables).
- Set random seeds and record package versions, so results can be reproduced.
- Before sharing a notebook, restart and run all cells from the top to make sure it works in order.
- Check counts and missing values at every step; most errors in clinical analyses come from data handling, not from models.
Cloud notebooks and patient data
- A personal Colab or Google Drive account is not an approved system for identifiable patient data. Real clinical projects belong in environments your organisation has approved, under its data-protection agreements.
Exercise
Set up a working Python environment, then load, check, summarise and plot a small synthetic clinical table, handling missing values explicitly.
Data: Synthetic table written into the notebook (no real patient data) (Generated in the notebook)
- Open the notebook in Colab (or locally) and run the version-check cell.
- Load the synthetic table and confirm the number of rows, columns and missing values.
- Create a 'tested' column and an 'hba1c_above_7' column that is missing, not False, when HbA1c is missing.
- Compute mean HbA1c and systolic blood pressure by sex, reporting the count behind each mean.
- Plot HbA1c against age and add a caption that states how many patients are shown.
The runnable notebook and worked solution will be published soon. You can work through the steps with the code on this page in the meantime.
Key takeaways
- Colab needs no setup; a local environment gives more control. Both run the same Python.
- pandas, scikit-learn and matplotlib cover most of this course's exercises.
- Missing values are silently skipped or turned into False; check them at every step.
- Keep work reproducible and keep real patient data out of personal tools.
Terms used: Synthetic data
Related: Diagnostic accuracy metrics, Healthcare data types, All exercises
FAQ
Do I need to know how to code to take this course?
No. Clinical-focus lessons can be read without running code. Basic Python, as in this lesson, makes the technical lessons and exercises much easier.
Is Google Colab free?
Colab has a free tier with usage limits, which is enough for this course's exercises. Paid tiers offer more computing power.
Which Python version should I install?
A currently supported Python 3 release; as of 2026 that means 3.11 or newer. Check python.org for the versions still receiving updates.
Can I upload hospital data to Colab to practise?
No. A personal Colab or Drive account is not an approved place for identifiable patient data. Practise with synthetic or open datasets.
Should I use notebooks or scripts?
Notebooks are good for learning and exploration. For code that will be reused or deployed, move it into scripts or packages with tests and version control.
Sources
- Python Software Foundation. Status of Python versions
- Python documentation. venv: creation of virtual environments
- pandas documentation. Working with missing data
- Google Colaboratory: frequently asked questions
- matplotlib documentation. Quick start guide
- Wilson G, et al. Good enough practices in scientific computing. PLoS Comput Biol 2017;13(6):e1005510. doi:10.1371/journal.pcbi.1005510
Educational content only. This material teaches methods; it is not clinical advice. Code, models and examples here are not validated medical devices and must not be used to make decisions about real patients without proper clinical validation, governance and any required regulatory approval. Examples use synthetic or openly licensed de-identified data only. Never paste identifiable patient information into public AI tools. Mentions of models, tools or vendors are for identification, not endorsement.