Skip to main content
v2026.11,986 entries · CC-BY 4.0

T-Test in Python: SciPy Tutorial, Code & Output

Master how to run and interpret a t-test in Python with SciPy, including one-sample, two-sample, and paired tests, assumption checks, and output fields.

Written and maintained by CASRAI Editorial Board

Published

On this page

To run a t-test in Python, researchers use the SciPy statistics library (scipy.stats), calling functions such as ttest_ind() for independent two-sample comparisons, ttest_1samp() for single-sample evaluations against a theoretical population mean, and ttest_rel() for paired repeated-measures designs. Executing these functions on numeric NumPy arrays or pandas Series computes the sample means, estimates standard error, and returns a TtestResult object containing the calculated t-statistic, two-tailed p-value, and degrees of freedom.

What Python is used for in research

Python has established itself as the standard programming language across scientific computing, computational biology, empirical economics, and academic research laboratories. Investigators rely on Python because it connects data ingestion, numerical filtering, inferential hypothesis testing, and publication-ready charting within a single scriptable pipeline. Rather than toggling between disconnected software applications for data cleaning and statistics, researchers execute continuous analytical pipelines that run deterministically across computing platforms.

The statistical capabilities of Python are provided by its scientific computing ecosystem. Core multi-dimensional array operations and linear algebra routines are handled by NumPy, while pandas structures heterogeneous experimental data into indexed tables. Statistical distributions and hypothesis testing procedures reside inside the SciPy stats module, which supplies implementations of classical parametric tests alongside non-parametric rank tests. For researchers evaluating experimental trials, the t-test remains the fundamental inferential tool used to decide whether observed differences between treatment cohorts, control conditions, or reference standards reflect genuine population effects rather than random sampling fluctuations.

Beyond isolated calculations, Python provides reproducibility and auditability for research workflows. Graphical statistical programs can allow unrecorded procedural adjustments, whereas Python scripts record every parameter, missing-data decision, and variance assumption. This transparency allows co-investigators, institutional review boards, and peer reviewers to reproduce every statistical finding directly from raw observations.

How to install or access Python

Accessing Python for scientific research begins with installing an official distribution from the Python Software Foundation at python.org. This provides the standard CPython runtime and the package installer pip. In university computing clusters and high-performance computing centers, system administrators typically manage Python versions through environment modules, accessed using shell commands such as module load python/3.11.

To avoid package version conflicts between separate research projects, scientific best practice requires isolating dependencies using Python virtual environments. Researchers initialize and activate a dedicated environment from the terminal:

python3 -m venv stats_env
source stats_env/bin/activate

Once the environment is activated, the core scientific stack is installed from the Python Package Index:

pip install numpy scipy pandas matplotlib

Interactive exploratory data analysis is commonly conducted through JupyterLab or IDEs such as VS Code. Modern releases of SciPy (such as versions 1.10 through 1.18) provide the structured TtestResult container for statistical results and require Python 3.9 or newer.

What are 5 data types in Python?

The five primary built-in data types in Python are integers (int), floating-point numbers (float), strings (str), booleans (bool), and lists (list), as documented in the Python Standard Library specifications. Selecting and maintaining appropriate data types is critical for statistical computing because routines in SciPy require numeric types and fail if passed character strings or unsupported objects.

  • Integer (int): Whole numbers without decimal components, representing sample counts (such as n = 45), integer degrees of freedom, or discrete observation tallies.
  • Floating-point (float): Real numbers containing decimal fractions, used for continuous measurements (such as enzyme activity or blood pressure), calculated t-statistics, and p-values.
  • String (str): Text character sequences enclosed in quotation marks, used for categorical cohort identifiers (such as "Control" or "Active") and variable column headers.
  • Boolean (bool): Binary logical values (True or False), passed into statistical routines to control algorithm parameters such as equal_var=False.
  • List (list): Ordered, mutable sequence collections storing series of observations before conversion into numerical NumPy arrays.

How to code “I love you” in Python?

To code “I love you” in Python, execute the built-in print function with the string literal: print("I love you"). In larger software programs, developers also generate dynamic messages using formatted string literals, such as message = f"I love {recipient}", or define reusable functions that return text strings.

In computational research environments, writing a simple print statement serves as the standard sanity test to confirm that a fresh Python virtual environment, interactive terminal, or cluster execution node is active and interpreting syntax correctly before launching analytical pipelines.

How to run a t-test in Python step by step

Executing an inferential t-test in Python requires a systematic workflow that validates distribution assumptions before calculating test statistics. The numbered procedure below walks through loading data, testing assumptions, executing the appropriate t-test, and extracting inferential results using scipy.stats.

  1. Import numerical and statistical modules: Load NumPy for vector manipulation and the stats subpackage from SciPy.

    import numpy as np
    from scipy import stats
  2. Prepare experimental data vectors: Structure observational cohorts as numeric NumPy arrays or pandas Series, ensuring missing records are handled properly.

    group_a = np.array([21.4, 23.1, 19.8, 22.5, 20.7, 24.2, 21.9, 22.8, 20.1, 23.5])
    group_b = np.array([25.3, 26.8, 24.1, 27.5, 25.9, 28.2, 26.4, 27.1, 24.8, 26.9])
  3. Check distribution normality: Use the Shapiro-Wilk test (stats.shapiro) to assess whether sample distributions depart from normality. The null hypothesis specifies that values are normally distributed. If the resulting p-value exceeds 0.05, normality is retained.

    stat_a, p_norm_a = stats.shapiro(group_a)
    stat_b, p_norm_b = stats.shapiro(group_b)
    print(f"Normality p-values: Group A = {p_norm_a:.4f}, Group B = {p_norm_b:.4f}")
  4. Test homogeneity of variance: Evaluate whether group variances are equal using Levene’s test (stats.levene). If Levene’s test produces a p-value less than 0.05, the assumption of equal variance is rejected, requiring Welch’s t-test.

    stat_lev, p_var = stats.levene(group_a, group_b)
    print(f"Levene test p-value: {p_var:.4f}")
  5. Execute the t-test: Call the specific test function matching your design. Set equal_var=False to execute Welch’s t-test for unequal variances, or equal_var=True for Student’s pooled-variance test.

    res_welch = stats.ttest_ind(group_a, group_b, equal_var=False)
  6. Extract statistics and confidence limits: Access the calculated attributes from the returned TtestResult object.

    print(f"t-statistic: {res_welch.statistic:.4f}")
    print(f"p-value:     {res_welch.pvalue:.4e}")
    print(f"df:          {res_welch.df:.2f}")
    
    ci = res_welch.confidence_interval(confidence_level=0.95)
    print(f"95% CI:      [{ci.low:.4f}, {ci.high:.4f}]")

When to use 1 or 2 sample t-test?

Use a 1-sample t-test when comparing an empirical sample mean against an external standard, certified benchmark, or theoretical population value. Use a 2-sample t-test when comparing two distinct groups to determine whether the difference between their means is statistically significant.

A 1-sample t-test (computed with scipy.stats.ttest_1samp) evaluates one data vector against a fixed scalar value (popmean). For example, analytical laboratories run 1-sample t-tests to verify whether an assay calibration run differs significantly from an established 100.0 mg reference standard.

In contrast, a 2-sample t-test evaluates differences between two observational vectors. Within 2-sample testing, researchers distinguish between independent and paired designs. Independent 2-sample tests (scipy.stats.ttest_ind) compare separate cohorts, such as an experimental therapy group versus an untreated control group. Paired 2-sample tests (scipy.stats.ttest_rel) are applied when measurements are gathered from the same subjects across repeated occasions, such as baseline and post-treatment evaluations.

How to read the output

Modern SciPy releases encapsulate statistical output within a structured TtestResult object. Interpreting each attribute allows researchers to understand evidentiary strength and report findings accurately in scholarly papers.

The statistic attribute represents the calculated t-score. The t-statistic measures the ratio between the observed mean difference and the standard error of that difference. An absolute t-value substantially greater than zero indicates that the divergence between sample means is noticeably larger than expected from sampling variability alone. A positive t-value means the first sample has a higher mean than the second sample, while a negative t-value indicates the reverse.

The pvalue attribute reports the two-tailed probability of observing a test statistic at least as extreme as the calculated t-score, assuming the null hypothesis of equal means is true. When this probability is below the established alpha threshold (conventionally α = 0.05), the null hypothesis is rejected. Setting alternative='less' or alternative='greater' performs directional one-sided testing. In formal methodology, the p-value threshold reflects statistical evidence against the null rather than clinical effect size.

The df attribute indicates the degrees of freedom. In Student’s pooled-variance t-test, degrees of freedom equal the combined sample size minus two (df = n1 + n2 – 2). When running Welch’s t-test with equal_var=False, SciPy calculates fractional degrees of freedom using the Welch-Satterthwaite equation, accounting for unequal variances and sample sizes. The theoretical foundation is detailed in our guide on Student’s t-test p-value calculation.

The confidence_interval(confidence_level=0.95) method computes the 95% confidence interval for the true population mean difference. If this interval spans zero, the observed group difference is not statistically significant at the 5% level.

Is p less than 0.001 significant?

Yes, a p-value less than 0.001 is statistically significant under standard scientific thresholds, including α = 0.05, α = 0.01, and α = 0.001. In scientific journals adhering to APA or biomedical editorial guidelines, p-values smaller than 0.001 are formatted as “p < .001" rather than reported in scientific notation.

A p-value below 0.001 indicates that there is less than a 0.1% chance of observing a difference this large if the null hypothesis were true, providing very strong evidence against the null hypothesis.

However, statistical significance must not be confused with substantive scientific importance. In large experimental datasets, minor differences of little practical consequence can reach statistical significance below 0.001. Investigators should always pair p-values with standardized effect size measures such as Cohen’s d to communicate the magnitude of the experimental effect.

When reporting results in publications, use standard format:

“An independent Welch’s t-test indicated that participants in the intervention condition had higher performance scores (M = 26.4, SD = 1.3) than control participants (M = 22.1, SD = 1.4); t(17.8) = 7.12, p < .001, 95% CI [3.04, 5.56], Cohen's d = 3.18."

Troubleshooting Python

When analyzing empirical research data in Python, statistical routines can encounter runtime exceptions or unexpected results. The following points outline common failure modes and solutions:

  • Missing values and NaN results: SciPy functions default to nan_policy='propagate'. If any input array contains missing data (np.nan), the function returns NaN for the t-statistic and p-value without raising an error. To automatically exclude missing values during testing, supply nan_policy='omit', or filter data beforehand using pandas dropna().
  • Incorrect data types and TypeError: Datasets loaded from external CSV files often parse numerical fields as string objects due to formatting symbols or non-numeric annotations. Passing non-numeric arrays to ttest_ind triggers a TypeError. Convert data columns to numeric format using pd.to_numeric(df['column'], errors='coerce').
  • Zero variance and division by zero: If all observations within a sample have identical values, the sample variance equals zero. This creates a division-by-zero condition in the t-test formula, producing a runtime warning and returning NaN. Verify variance before running batch tests.
  • Non-normality in small samples: In small samples (sample sizes under 20), severe departures from normality undermine the reliability of the t-test. When the Shapiro-Wilk test indicates non-normality (p less than 0.05), switch to non-parametric equivalents: the Mann-Whitney U test (scipy.stats.mannwhitneyu) for independent groups, or the Wilcoxon signed-rank test (scipy.stats.wilcoxon) for paired data.
  • Heteroscedasticity and unequal variances: Applying Student’s pooled t-test to cohorts with unequal variances inflates false positive rates. Modern biostatistical guidelines recommend using Welch’s t-test (equal_var=False) as the default standard for independent two-sample tests.

Free alternatives to Python

While Python is well-suited for automated pipelines and general scripting, several free and open-source software tools offer dedicated environments for hypothesis testing in research.

The leading statistical alternative is R, which was designed from the ground up for data analysis. In R, independent and paired t-tests are executed using the native stats::t.test() function, which applies Welch’s correction by default. For syntax and output comparisons, refer to our guide on running a t-test in R. For basic spreadsheet analysis, researchers can also run comparisons using the T.TEST function in Excel.

For researchers who prefer interactive graphical software without writing code, JASP and Jamovi provide open-source desktop interfaces powered by R that generate formatted summary tables. In scientific computing, Julia provides high-performance testing through HypothesisTests.jl, while GNU Octave provides a scriptable numerical environment compatible with MATLAB syntax.

Software Tool Interface Mode Default Variance Assumption Welch Support Primary Academic Field
Python (SciPy) Programmatic (Script / Notebook) Equal (equal_var=True) Yes (equal_var=False) Data Science, Bioinformatics, Physics
R (stats) Programmatic (Script / Console) Unequal (Welch default) Yes (var.equal=TRUE for pooled) Biostatistics, Ecology, Psychology
Julia (HypothesisTests) Programmatic (Script / REPL) Unequal (Welch default) Yes (EqualVarianceTTest) Scientific Computing, Economics
GNU Octave Command-Line / Script Equal (Pooled variance) Yes (Welch formula implementation) Engineering, Signal Processing
JASP Graphical Desktop GUI User Selectable (Student / Welch) Yes (Checkbox selection) Psychology, Social Sciences
Jamovi Graphical Desktop GUI User Selectable (Student / Welch) Yes (Checkbox selection) Behavioral Sciences, Medicine

The data table below compares the specific programmatic functions, parameter switches, and output capabilities of Python statistical packages.

Frequently asked questions

What are 5 data types in Python?

The five core built-in data types in Python are integers (int), floating-point numbers (float), strings (str), booleans (bool), and lists (list). In SciPy statistical analysis, numeric observations must be stored as integers or floats, as string types trigger execution errors.

How to code “I love you” in Python?

In Python, you code “I love you” by calling the print function with a string: print("I love you"). In larger programs, developers also use formatted f-strings or custom helper functions to display textual messages.

When to use 1 or 2 sample t-test?

Use a 1-sample t-test when comparing a single empirical sample against an external reference value or theoretical population mean. Use a 2-sample t-test when comparing two distinct groups to determine whether their difference in means is statistically significant.

Is p less than 0.001 significant?

Yes, a p-value less than 0.001 is statistically significant across standard scientific thresholds, including 0.05 and 0.01. It indicates that the probability of observing such an extreme difference under a true null hypothesis is less than one in one thousand.

What is the difference between Student’s t-test and Welch’s t-test in Python?

Student’s t-test assumes that both groups have equal population variances and calculates a pooled variance estimate. Welch’s t-test relaxes this assumption, calculating adjusted degrees of freedom with the Welch-Satterthwaite equation. In SciPy, Welch’s test is enabled by setting equal_var=False.

How do you handle missing values when running a t-test in SciPy?

SciPy defaults to propagating missing values, returning NaN if any input vector contains missing entries. To automatically exclude missing values during calculation, pass nan_policy='omit' into the test function, or clean arrays beforehand using pandas dropna().

Sources

Data: Python Statistical Hypothesis Testing Libraries: Parameter and Capability Matrix

Comparative specifications, function signatures, variance assumptions, and output structures across core Python hypothesis testing functions, compiled from official SciPy and statsmodels documentation.

Python Statistical Hypothesis Testing Libraries: Parameter and Capability Matrix
FunctionPackageTest TypeDefault VarianceWelch OptionOutput FormatBuilt-in CI
scipy.stats.ttest_indSciPyIndependent 2-SampleEqual (Pooled)equal_var=FalseTtestResult objectconfidence_interval() method
scipy.stats.ttest_1sampSciPySingle SampleNot applicableNot applicableTtestResult objectconfidence_interval() method
scipy.stats.ttest_relSciPyPaired 2-SampleNot applicableNot applicableTtestResult objectconfidence_interval() method
statsmodels.stats.weightstats.ttest_indstatsmodelsIndependent 2-SamplePooled (usevar='pooled')usevar='unequal'Tuple (tstat, pvalue, df)Via CompareMeans summary
statsmodels.stats.weightstats.DescrStatsW.ttest_meanstatsmodelsSingle SampleSample varianceNot applicableTuple (tstat, pvalue, df)tconfint_mean() method

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about T-Test in Python: SciPy Tutorial, Code & Output

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →