In a nutshell
Python is a highly readable general-purpose language that has become a data-science standard. Like R, it is used to clean, analyse and visualise data once extracted with SQL — through the polars (data tables) and seaborn (charts) libraries. Above all, it is the reference language for machine learning, with the scikit-learn library. You often use it in Jupyter notebooks.
This article follows on from Why learn to code? and the introduction to R. It follows the same outline as the R article, so the two languages are easy to compare.
Why Python
R is a specialised language, designed for statistics. Python, on the other hand, is a general-purpose language, like C or Java: it was not designed for any particular field, but to write all kinds of programs readably. It is today the most widely used programming language in the world: it tops the TIOBE index, which measures the popularity of programming languages (October 2026). That gives it strengths complementary to R’s:
- Versatility: beyond data analysis, Python is used to automate tasks, handle files, query websites, build applications.
- Machine learning: the major machine learning and artificial intelligence libraries (scikit-learn, PyTorch…) are in Python. It is unavoidable once you move towards predictive modelling.
- Readability: its clean syntax makes it a good first language, including for those who have never programmed.
R or Python?
Both are excellent choices to start with. R is particularly well suited to biostatistics and statistical visualisation; Python is more versatile and unavoidable in machine learning. The most efficient path: start with the one your supervisors use, then discover the other when the need arises.
The working environment
In data science, you often write Python in Jupyter notebooks: a document that alternates code cells, their results (tables, charts) and explanatory text. It is ideal for exploring data step by step and sharing a commented analysis. To see one, open the 02_ml_mortality.ipynb notebook in the IDE of the Linkr demo: it trains a model predicting ICU mortality, cell by cell.
To write your own scripts and notebooks, the environments presented in the introduction to R also work for Python: Positron handles R and Python in the same interface, and VS Code is widely used by Python developers.
polars: working with data
polars is a modern, fast library for handling tabular data in Python. It organises data in an object called a DataFrame — a table with named rows and columns, like a spreadsheet. Its syntax is close to that of dplyr in R: you chain verbs that mirror the building blocks of a SQL query — filter() (like WHERE), select() (like SELECT), group_by() + agg() (like GROUP BY).
import polars as pl
# We create a table of patients with the columns sex, age and creatinine
patients = pl.DataFrame({
"sex": ["F", "M", "F", "F", "M", "F"],
"age": [72, 45, 34, 78, 60, 69],
"creatinine": [142, 88, 71, 156, 97, 168],
})
(
patients
.filter((pl.col("sex") == "F") & (pl.col("age") > 65)) # we keep women over 65
.group_by("sex") # we group by sex
.agg(
n=pl.len(), # we count the patients
mean_creat=pl.col("creatinine").mean(), # and compute the mean creatinine
)
) | sex | n | mean_creat |
|---|---|---|
| F | 3 | 155.333333 |
If you read the SQL and R articles, you recognise the same logic: filter rows, group, summarise. Only the syntax changes. In practice, you often load the data from a CSV file (a text table where columns are separated by commas) with pl.read_csv("patients.csv"), a very common exchange format.
As in R, a few commands come up at the very start of an analysis to understand the data:
patients.shape # we count the rows and columns
patients.describe() # we summarise each column (min, max, mean…)
patients.null_count() # we count the missing values per column
These three lines give a first picture of the structure and data quality.
A tidyverse equivalent in Python
Python has no tidyverse as such, but equivalent libraries exist for each use. Posit, the company behind RStudio and Positron, is also investing more and more in Python: Positron, Shiny and Great Tables now all work with both languages.
| Use | R | Python |
|---|---|---|
| Manipulate tables | dplyr | polars |
| Create charts | ggplot2 | seaborn, plotnine |
| Format result tables | gt | Great Tables |
| Build web applications | Shiny | Shiny for Python |
| Machine learning | tidymodels | scikit-learn |
Visualising with seaborn
matplotlib is the base library for plotting charts in Python: it lets you control every detail of a figure, but takes a lot of code. seaborn, built on top of it, simplifies common statistical charts. The code below reproduces the figure from the introduction to R: a scatter plot with a regression line and its confidence interval.
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style="whitegrid") # we pick a clean theme
ax = sns.regplot(data=patients, x="age", y="creatinine",
color="#2563eb") # we plot the points and the regression line, with its confidence interval
ax.set_title("Creatinine by age", fontweight="bold") # we add the title, in bold
ax.set(xlabel="Age (years)", ylabel="Creatinine (µmol/L)") # and the axis names
sns.despine(left=True, bottom=True) # we remove the frame
plt.show() # and we display the chart
As with ggplot2, a few lines are enough to get a clean figure. seaborn estimates the confidence interval by resampling (bootstrap), hence its slightly irregular outline. To see what is possible, browse the Python Graph Gallery, which shows hundreds of charts with their code.
Finally, if you come from R, plotnine even reproduces the ggplot2 syntax almost identically.
Shiny for Python: interactive web applications
As in R, Shiny lets you build interactive web applications in Python: users pick parameters from menus, and tables and charts update instantly. The principles are the same as those presented in the introduction to R. To get an idea of what is possible, browse the Shiny for Python gallery.
Machine learning with scikit-learn
scikit-learn is the reference library for machine learning in Python, and probably the most important Python library to know for health research. It offers a single interface to dozens of methods — logistic regression, random forest, gradient boosting, clustering… — as well as all the tools to prepare data and evaluate models.
The example below uses a dataset shipped with scikit-learn: 569 breast tumours, described by 30 measurements taken from images of biopsy samples, each classified as benign or malignant. We train a random forest on three quarters of the tumours, then measure how well it predicts the nature of the others.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
# We load the data: X holds the measurements, y the diagnosis
X, y = load_breast_cancer(return_X_y=True)
# We split training (75%) and test (25%) data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
model = RandomForestClassifier(random_state=42) # we pick a random forest
model.fit(X_train, y_train) # and train it on the training data
proba = model.predict_proba(X_test)[:, 1] # we predict the probability on the test data
print(f"AUC: {roc_auc_score(y_test, proba):.3f}") # and compute the AUC AUC: 0.996
You find the same steps as with tidymodels in R: pick a model, train it, predict, evaluate. The AUC measures how well the model tells the two classes apart: 1 is a perfect prediction, 0.5 is chance. This dataset is deliberately easy; on real data, performance is rarely this high.
Python and Linkr
As explained in the introduction to R, code lets you extend an analysis beyond what the Study Designer generates automatically: the tool to design and frame, the code to explore without limits. Python is in particular the best choice as soon as you want to train a prediction model on data extracted from a warehouse.
As with R, you can write and run Python directly in Linkr’s IDE, including in the browser with nothing to install: try it in the demo.
Resources to learn
What you'll learn
- The language foundations: variables, conditions, loops, functions.
- Accessible to complete beginners, recommended by our students.
- Budget around ten hours rather than the six advertised if you start from scratch.
What you'll learn
- Read a file, filter, select, group and aggregate a DataFrame.
- Start with Getting started, then the Expressions section.
What you'll learn
- Build statistical charts: scatter plots, distributions, comparisons between groups.
- Many ready-to-adapt examples for your own data.
Recommended path for Python
- Learn the language with the OpenClassrooms course (~10 h), writing code in the IDE of the Linkr demo: nothing to install.
- Continue with polars to manipulate tables, then seaborn to visualise.
- Machine learning comes later, in the dedicated section on AI in healthcare — introductory courses (like Andrew Ng’s on Coursera) are more than enough to begin.
- Python is a general-purpose language, like C or Java, and the most widely used in the world: a data-science standard and the reference for machine learning.
- polars handles tables with the same logic as
dplyrand SQL; equivalents exist for most tidyverse libraries. - seaborn produces a clean figure in a few lines, like ggplot2 in R.
- Shiny also exists in Python to build interactive web applications.
- scikit-learn is the reference library for machine learning.
- You can code in Python in Linkr's IDE, including in the browser via the demo.