Skip to content

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 ColabLocal environment
SetupNone: open a notebook in the browser with a Google accountInstall Python, create an environment, install packages
CostFree tier with usage limits; paid tiers availableFree; uses your own computer
FilesTemporary: files are lost when the session ends unless saved to Drive or downloadedStay on your disk
Data protectionData goes to a third-party cloud service; do not upload identifiable patient data to a personal accountData stays on your machine, subject to your organisation's policies
Best forLearning, this course's exercises, quick experimentsLonger 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.

python
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__}")
Check your Python and library versions. Output differs between machines.

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.

bash
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
Create and activate a virtual environment, install the core packages and record their versions.
  • 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.

python
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
Load six synthetic patients, describe the numeric columns and count missing values.
  • describe() quietly skips missing values: the HbA1c count is 5, not 6. Always check counts before trusting a mean.

Grouping, new columns and a hidden trap

python
df["hba1c_above_7"] = df.hba1c > 7.0
print(df.groupby("sex")[["hba1c", "systolic_bp"]].mean().round(1))
print(df[["patient_id", "hba1c", "hba1c_above_7"]])

#      hba1c  systolic_bp
# sex
# F      7.8        133.7
# M      7.8        146.7
#
#   patient_id  hba1c  hba1c_above_7
# 0        s01    7.9           True
# 1        s02    6.4          False
# 2        s03    8.6           True
# 3        s04    NaN          False
# 4        s05    6.9          False
# 5        s06    9.1           True
Continuing from the previous block.
  • Patient s04 has no HbA1c result, but the comparison marks them False, as if their HbA1c were known to be 7% or below. In a real analysis this would wrongly count an untested patient as controlled.
  • Handle missing values explicitly, for example by keeping a separate 'tested' column, before creating derived variables.

A first chart

python
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)
Continuing from the previous block: a scatter plot with a reference line, saved as an image.
  • 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)

  1. Open the notebook in Colab (or locally) and run the version-check cell.
  2. Load the synthetic table and confirm the number of rows, columns and missing values.
  3. Create a 'tested' column and an 'hba1c_above_7' column that is missing, not False, when HbA1c is missing.
  4. Compute mean HbA1c and systolic blood pressure by sex, reporting the count behind each mean.
  5. 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.

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.