BP201T · Semester 2 · B.Pharm

Unit V — Statistical Analysis Using Python — Case based learning

Applied Biostatistics and Data Analytics for Pharmaceutical Sciences

The complete notes for this unit, chapter by chapter. Download the PDF to study offline.

Topics in this unit

  • Descriptive statistics, correlation analysis, and linear regression with pharmaceutical datasets
  • SciPy, Statsmodels, and scikit-learn concepts
  • Output summaries and p-values
  • Statistical-report preparation

Full notes for this unit

Read the notes here, or download the PDF below for offline study. For education and exam preparation; check current official references before relying on legal, clinical or dosage details.

Chapters in this unit

Chapter 5: Statistical Analysis Using Python: Case-Based Learning

Learning objectives

After studying this chapter, you will be able to:

  1. Run a complete descriptive analysis on a pharmaceutical dataset with Pandas.
  2. Compute correlation with SciPy and interpret the coefficient and its p-value.
  3. Fit a simple linear regression with Statsmodels and with Scikit-learn.
  4. Read an OLS output summary: coefficients, standard errors, p-values, R-squared.
  5. Write a short, honest statistical report of your findings.

The case dataset (illustrative)

A small illustrative trial dataset — 12 patients, antihypertensive drug:

Patientdose_mgage_yrsbp_drop (mmHg)
110454
215527
320388
4256111
5304912
6355514
7404215
8455818
9504719
10556321
11605122
12654424

This dataset is illustrative — invented only to teach the workflow, not real trial data.

Case step 1 — descriptive statistics with Pandas

  • import pandas as pd df = pd.DataFrame({
  • "dose_mg": [10,15,20,25,30,35,40,45,50,55,60,65],
  • "age_yrs": [45,52,38,61,49,55,42,58,47,63,51,44],
  • "bp_drop": [4,7,8,11,12,14,15,18,19,21,22,24],
  • }) print(df.describe().round(2))
  • Line-by-line: build the DataFrame from three lists; .describe() computes count, mean, std, min, quartiles, max for every numeric column; .round(2) tidies decimals.

Sample output (computed by running the code):

  • dose_mg age_yrs bp_drop
count mean std min12.00 37.50 18.03 10.0012.00 50.42 7.75 38.0012.00 14.58 6.39 4.00
25%23.7544.7510.25
50%37.5050.0014.50
75% max51.25 65.0055.75 63.0019.50 24.00
  • Interpretation for the report: 12 patients, mean age ~50 years, mean BP drop ~14.6 mmHg (SD 6.4).
  • Doses span 10–65 mg evenly (mean = median = 37.5 — symmetric by design). No missing values (count = 12 everywhere).
  • Key takeaway: .describe() is always step one — it checks data quality (missing values, weird ranges) and gives the story's headline numbers.

Case step 2 — correlation analysis with SciPy

  • from scipy import stats r, p = stats.pearsonr(df["dose_mg"], df["bp_drop"]) print("r =", round(r, 3), " p =", p)
  • Line-by-line: stats.pearsonr(x, y) returns two things — the Pearson r and the p-value testing H0: "true correlation is zero". (Age vs BP drop gives r ≈ 0.22 — weak, as the matrix below shows.)

Sample output (values computed from the data):

r = 0.997 p < 0.0001

  • Interpretation: r = 0.997 is an extremely strong positive correlation; p < 0.0001 means such a strong link would almost never appear by chance if dose and response were truly unrelated — reject H0. The full correlation matrix (from df.corr()) is: dose_mg age_yrs bp_drop

dose_mg age_yrs bp_drop 1.000 0.161 0.997 0.161 1.000 0.224 0.997 0.224 1.000

Age barely correlates with anything (r ≈ 0.16–0.22) — dose is the driver.

  • Key takeaway: SciPy hands you r and its p-value together — strength and evidence in one line.

Case step 3 — linear regression with Statsmodels

Statsmodels is the library for statistical modelling — its summaries read like a textbook page.

  • import statsmodels.formula.api as smf model = smf.ols("bp_drop ~ dose_mg", data=df).fit() print(model.summary())
  • Line-by-line: smf.ols("bp_drop ~ dose_mg", data=df) declares the model "predict bp_drop from dose_mg" (~ reads as "modelled by"); .fit() finds the least-squares line; .summary() prints the full statistical report.

How to read the summary (the four things that matter):

  1. Coefficients table — the fitted line from our data: intercept ≈ 1.34, slope ≈ 0.353, i.e. bp_drop = 1.34 + 0.353 × dose. Each extra mg predicts ~0.35 mmHg more BP drop.
  2. P>|t| column — the p-value for each coefficient. Here both are far below 0.05: the slope is statistically significant; dose genuinely predicts response.
  3. R-squared ≈ 0.993 — the model explains 99.3% of the variation in BP drop. (R2 = r2 = 0.9966² ≈ 0.993.) Near 1 = the line fits beautifully.
  4. nobs = 12 — always check the sample size; great R2 on 12 illustrative points is a teaching demo, not a drug approval.
  • Key takeaway: The summary answers three questions: what is the equation (coef), is it real (p-values), and how well does it fit (R-squared).

Case step 3 (alternative) — regression with Scikit-learn

Scikit-learn is the library for machine learning — less statistical detail, built for prediction pipelines.

  • from sklearn.linear_model import LinearRegression

X = df[["dose_mg"]] y = df["bp_drop"] reg = LinearRegression().fit(X, y) # predictors must be a 2-D table # outcome is a single column # fit the line

  • print("Slope:", reg.coef_, " Intercept:", reg.intercept_) print("R2:", reg.score(X, y)) print("Predicted drop at 70 mg:", reg.predict([[70]]))
  • Line-by-line: wrap the dose column in double brackets (sklearn needs 2-D input); .fit(X, y) learns the line;
  • .coef_ / .intercept_ reveal it; .score returns R2; .predict([[70]]) forecasts a new dose.

Sample output (same least-squares maths as Statsmodels):

  • Slope: [0.3531] Intercept: 1.3403
  • R2: 0.9932
  • Predicted drop at 70 mg: [26.06]
  • Interpretation: Identical line (0.353 slope, 1.34 intercept) — the libraries agree, as they should. But note: 70 mg lies outside our 10–65 mg data range, so 26.06 mmHg is an extrapolation — flag it as uncertain, never as a promise.

Statsmodels vs Scikit-learn — which to use?

  • Statsmodels Scikit-learn
StrengthFull statistical summary (p-values, CIs, R2)Prediction pipelines, machine learning
Use whenYou must explain and justify the modelYou must predict new cases at scale
Exam tip"Interpret the output" → Statsmodels"Predict / deploy" → Scikit-learn
  • Key takeaway: Same line, different jobs — Statsmodels explains, Scikit-learn predicts.

Case step 4 — writing the statistical report

A good report is short and honest. Structure:

  1. Objective — one line: what question the analysis answers.
  2. Data & methods — dataset description (n, variables), methods used (descriptive stats, Pearson r, OLS regression), software (Python, Pandas/SciPy/Statsmodels).
  3. Results — numbers with interpretation: "Mean BP drop was 14.6 mmHg (SD 6.4). Dose and BP drop correlated strongly (r = 0.997, p < 0.0001). The fitted line was bp_drop = 1.34 + 0.353 × dose (R² = 0.993); the slope was statistically significant (p < 0.05)."
  4. Limitations — small illustrative sample (n = 12); association is not causation; prediction at 70 mg is extrapolation.
  5. Conclusion — one careful line: "Higher doses were associated with greater BP reduction in this illustrative dataset; confirmatory trials are needed."
  • Golden rules: report effect sizes with p-values (never p-values alone); state limitations plainly; never claim causation from correlation; mark illustrative data as illustrative.
  • Key takeaway: A report = question → methods → numbers → honest limits → careful conclusion.

Pharmacy relevance (Unit V)

  • Trial analysis: this exact workflow (describe → correlate → regress → report) is how Phase II dose- finding results are analysed.
  • QC trending: regressing assay values over months detects drift before batches fail.
  • Regulatory writing: agencies expect p-values, CIs, and clear limitations — exactly this report structure.

Common confusions

  1. Statsmodels vs Scikit-learn output: same line, different detail — don't panic when numbers match but layouts differ.
  2. R2 vs r: R2 (0–1) is the fraction of variation explained; r (−1 to +1) is the correlation. In simple regression, R2 = r2.
  3. p < 0.05 on the slope means the relationship is statistically real — not that it is clinically big.
  4. Prediction vs explanation: a model can predict well (high R2) without proving why.

Common mistakes

  • Forgetting df[["dose_mg"]] needs double brackets in sklearn (single brackets crash .fit).
  • Reporting the regression equation without R2 or p-values.
  • Extrapolating beyond the data range without a warning.
  • Presenting illustrative/demo data as if it were real trial evidence.

One-minute revision (Unit V)

  • Workflow: describe → correlate → regress → report.
  • Pandas .describe() = data health-check + headline numbers. scipy.stats.pearsonr → r and its p-value.
  • Statsmodels ols("y ~ x").fit().summary() → coefficients, p-values, R2 (explanation).
  • Sklearn LinearRegression().fit(X, y) → .coef_, .intercept_, .score, .predict (prediction).
  • Report structure: objective → methods → results → limitations → careful conclusion.
  • Never: p-value without effect size; causation from correlation; silent extrapolation.

Practice questions (Unit V)

MCQs

  1. df.describe() does NOT show: a) mean b) 25th percentile c) p-value d) max
  2. In a Statsmodels OLS summary, R² = 0.93 means: a) r = 0.93 b) 93% of variation in y explained by the model c) p = 0.07 d) slope = 0.93
  3. For sklearn's .fit(X, y), X must be: a) 1-D b) 2-D c) A list d) A dictionary
  4. The most honest next line after "r = 0.9, p < 0.001" in a report is: a) "X causes Y" b) A limitation note c) Nothing d) "p proves causation"

Short questions

  1. List the four sections of a statistical report and one line each should contain.
  2. Distinguish the roles of Statsmodels and Scikit-learn in one table.
  3. Your regression predicts well but n = 12. Write the limitation sentence for the report.

Long / application-based

Download notes

Save the PDF to study offline. If it opens in your browser instead, use the viewer’s download button.

For education and exam preparation only, not medical advice or current regulatory guidance.

Other units in this subject

Back to BP201T notes