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

NumPy trapz: Syntax, Migration and Examples

Move from NumPy trapz to trapezoid with a checked irregular-sampling example, array-axis checks and an API migration table.

Written and maintained by CASRAI Editorial Board

Published

On this page

NumPy trapz is the former function for integrating sampled values with the composite trapezoidal rule. It was deprecated in NumPy 2.0 and removed in 2.4; use numpy.trapezoid for current code. The example below shows how irregular sampling, array axes and coordinate direction affect the result.

What it is used for in research

Trapezoidal integration combines the areas between adjacent observations. A researcher with recorded signal values and their measurement coordinates can calculate an approximate integral directly from those samples. The historical NumPy trapz documentation describes this operation on one-dimensional slices of an array. It does not require you to supply a callable equation for the signal.

The distinction matters when choosing an integration workflow: observations are already fixed, while a mathematical function can be evaluated at additional locations. For the latter workflow, see integrating callable functions with scipy.integrate.quad. This guide concentrates on sampled arrays and on repairing notebooks that still contain the old NumPy name.

In a simple illustrative sensor experiment, signal values might be recorded at several elapsed times. Integrating against time produces a signal-times-time quantity. That description does not make the result a calibrated physical measurement: the meaning still depends on what the signal represents. Keep the coordinate units, signal units and integration window alongside the reported number.

Legacy syntax and the current replacement

# Historical NumPy API: unavailable in NumPy 2.4 and later
np.trapz(y, x=None, dx=1.0, axis=-1)

# Current NumPy API, introduced in NumPy 2.0
np.trapezoid(y, x=None, dx=1.0, axis=-1)

Here y contains the observations, x supplies their coordinates, dx gives constant spacing when x is omitted, and axis chooses the dimension to integrate. The default axis is the last one. The historical and current reference pages use the same argument structure. NumPy’s 2.0 and 2.4 release notes establish the deprecation and removal respectively; an old documentation page is therefore not evidence that np.trapz remains available in a current installation.

Install or access

NumPy’s official installation page provides a pip workflow and recommends using a virtual environment for dependency management. For a new environment on macOS or Linux, its documented sequence is:

python -m venv my-env
source my-env/bin/activate
pip install numpy

The source command activates the environment in a compatible Unix shell; it is not a Python statement. Run the installation commands in a terminal, then execute the analysis in that environment. Conda users can instead follow the official conda installation route. Keep an existing research project’s dependency policy in view before changing its software environment.

In the Python session that will run the analysis, inspect the imported version:

import numpy as np
print(np.__version__)

Use np.trapezoid in the examples below with NumPy 2.0 or later. If a preserved notebook uses np.trapz, make the API migration explicit in its analysis code. For collaborating on a conda-based project, sharing a reproducible conda environment provides the surrounding environment workflow.

Step-by-step task: integrate irregular research samples

This worked example is an illustrative composite with synthetic sensor data, not observations from a published experiment. Four elapsed times, measured in seconds, have signal readings in arbitrary units. The unequal intervals are intentional: they expose an error that a successful function call alone would not reveal.

  1. Define paired coordinates and readings. Keep the time associated with each reading. In this example the arrays have matching lengths and are already chronological.
  2. Pass the coordinates explicitly. Use x=t so that each interval contributes its actual width rather than a default unit width.
  3. Calculate the scalar integral. Retain the interval and units with the result.
  4. Check it by hand. Reconstruct the three adjacent trapezoids before applying the same analysis to a larger dataset.
import numpy as np

t = np.array([0.0, 1.0, 3.0, 6.0])
signal = np.array([0.0, 2.0, 4.0, 9.0])

area = np.trapezoid(signal, x=t)
print(area)
# 26.5

The arithmetic uses each pair’s average height multiplied by its coordinate difference:

A = Σ [(y[i] + y[i+1]) / 2] × (x[i+1] − x[i]). Here i indexes adjacent pairs, y is the signal, x is elapsed time, and Σ means to add all interval contributions.

  • From 0 to 1 second: (0 + 2) / 2 × (1 − 0) = 1.
  • From 1 to 3 seconds: (2 + 4) / 2 × (3 − 1) = 6.
  • From 3 to 6 seconds: (4 + 9) / 2 × (6 − 3) = 19.5.

The sum is 1 + 6 + 19.5 = 26.5 signal-unit seconds. The code and hand calculation therefore agree. This verifies the numerical procedure on these inputs; it does not assert that the synthetic signal represents any particular laboratory process.

Check the spacing assumption

Omitting x changes this calculation. The documented default is dx=1, so the call below treats the readings as if they were separated by one coordinate unit:

print(np.trapezoid(signal))
# 10.5

That total comes from 1 + 3 + 6.5. It describes the same four heights on a different coordinate grid. A plausible result is therefore insufficient evidence that the integration represents the measurement schedule. Supplying a single dx cannot encode the three different widths in this example.

For a genuinely uniform grid, constant spacing is a concise alternative. With the same illustrative signal and a hypothetical two-second spacing, np.trapezoid(signal, dx=2.0) gives 21.0. That is a separate sampling assumption, not a correction for the original irregular times.

Output and how to read it

The NumPy reference describes a scalar result for one-dimensional input and an array with one fewer dimension for multidimensional input. Reading that output requires knowing which dimension represents samples. The following extension uses two synthetic traces measured at the same four times:

signals = np.array([
    [0.0, 2.0, 4.0, 9.0],
    [0.0, 4.0, 8.0, 18.0],
])
areas = np.trapezoid(signals, x=t, axis=1)
print(areas)
# [26.5 53. ]

Rows represent traces and columns represent observation times, so axis=1 integrates across the columns. The two returned values preserve the two trace identities. The second trace is exactly twice the first, making the doubled result a useful independent check for this constructed example.

If the same data are arranged with time down the rows, transpose the matrix and integrate with axis=0. That produces the same two results. State this layout in the code rather than relying on a default that another analyst may misread. For selecting windows or reversing paired observations, see NumPy slicing and array views.

Coordinate direction is part of the calculation

NumPy’s current documentation explicitly says that coordinates are used in their supplied sequence rather than sorted. Reversing both arrays reverses the integration direction:

reverse_area = np.trapezoid(signal[::-1], x=t[::-1])
print(reverse_area)
# -26.5

This negative value follows from negative interval widths. It does not mean the positive signal was changed to negative readings. Sorting only the coordinate array would instead break the measurement pairs. For an ordinary chronological signal, preserve the pairing when establishing time order; for a parametric trajectory, ordering is part of the path itself.

Describe what the number measures

A reproducible description for the synthetic example is: “Composite trapezoidal integration of four illustrative signal readings over 0–6 seconds, using their supplied irregular time coordinates, gave 26.5 arbitrary-unit seconds.” This identifies the method, interval, spacing treatment and units without implying that the synthetic data came from a real instrument.

The returned number is an approximation from the supplied points. Neither API signature returns an uncertainty estimate alongside the area. Do not report a scalar output as an estimated measurement error. In this constructed example, the hand calculation verifies the implementation and inputs; it cannot establish how an unobserved signal behaved between samples.

Troubleshooting

AttributeError after upgrading NumPy

For a call to np.trapz under NumPy 2.4 or later, use np.trapezoid. The removal is documented in NumPy’s own release notes. This is an API-name migration; do not reverse y and x while replacing the name. Historical code written as np.trapz(signal, t) becomes np.trapezoid(signal, t).

Record the dependency version with the notebook and rerun its numerical checks after the change. If code is maintained for multiple older NumPy releases, define and test that supported range explicitly rather than assuming every release exports the replacement name: numpy.trapezoid was introduced in 2.0.

A result that looks too small, negative or unexpectedly shaped

Start with the three diagnostic checks already demonstrated: compare actual coordinate widths with the unit-spacing assumption, inspect coordinate direction, and identify the sample axis. These produce different outcomes even when the function executes without an error. In the illustrative data, 10.5 versus 26.5 diagnoses spacing, −26.5 diagnoses reversal, and two results rather than one follow from integrating two traces.

Check that the number of coordinates matches the selected sample dimension. After transposing or selecting a data window, recheck both arrays together. A troubleshooting printout of the coordinates, readings and chosen axis is more informative than changing axis repeatedly until a call happens to run.

A gap between observations needs an analysis decision

Consider the constructed readings at 1 and 3 seconds. Their trapezoid contributes 6 because the method connects their heights across the full two-second interval. If that interval instead represents a gap you want excluded, the original calculation does not express that intention. Define separate continuous windows before integrating them, or document another analysis policy appropriate to the experiment.

Likewise, replacing an absent reading with zero changes the adjacent trapezoids. Treat that as a data-processing choice with scientific consequences. Keep the original samples and explain any exclusions or replacements in the analysis record; changing a function name does not settle those decisions.

Free alternatives

The following documented Python functions cover different output needs within the NumPy and SciPy ecosystem. The data table below traces the NumPy API from its historical reference through deprecation and removal.

Research task Function Documented distinction
One trapezoidal total per trace numpy.trapezoid Current NumPy sampled-array integration, with an explicit integration axis.
The same rule in an existing SciPy workflow scipy.integrate.trapezoid Composite trapezoidal integration using x or constant dx.
A running accumulated integral scipy.integrate.cumulative_trapezoid Returns intermediate integrals; initial=0 retains the input length.
Sampled-data integration using Simpson’s rule scipy.integrate.simpson Uses a different integration rule; its polynomial exactness depends on sampling conditions.

For the illustrative signal, scipy.integrate.cumulative_trapezoid(signal, x=t, initial=0) returns [0, 1, 7, 26.5]. The last element equals the scalar trapezoidal total. With its default initial=None, the cumulative result has one fewer element along the integration axis, so decide how that output will align with a time-series plot.

SciPy documents Simpson’s rule as exact for polynomials through degree three with an odd number of equally spaced samples; for unequal spacing, the stated exactness is through degree two. This is a mathematical condition, not a guarantee of accuracy for an arbitrary noisy signal. Choose the method to match the analysis and sampling design, and preserve its name with the reported result.

Sources

Data: NumPy trapz API migration by release

Original compilation of the NumPy 1.25 API reference, NumPy 2.0 and 2.4 release notes, and the current trapezoid reference. The rows distinguish documented historical availability, deprecation and removal; version labels identify releases rather than calendar dates.

NumPy trapz API migration by release
NumPy releasetrapz statustrapezoid statusImplication for analysis code
1.25Documented public APIIntroduced later, in NumPy 2.0Historical notebooks may call np.trapz(y, x=None, dx=1.0, axis=-1).
2.0DeprecatedIntroduced in this releaseNumPy directs users to np.trapezoid or scipy.integrate functions.
2.4RemovedThe NumPy replacement named in the removal notesReplace calls to np.trapz with np.trapezoid; preserve observation and coordinate argument order.

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 · free to try

Ask about NumPy trapz: Syntax, Migration and Examples

2 free questions a day, no account.

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 →