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

NumPy pad (np.pad): Syntax, Modes and Examples

np.pad adds a border to a NumPy array. See pad_width forms, every mode compared on one input, padding to a target shape, and common errors.

Written and maintained by CASRAI Editorial Board

Last updated

np.pad adds a border of new elements to an array and returns a new, larger array. The call is numpy.pad(array, pad_width, mode='constant', **kwargs): pad_width says how many elements to add before and after each axis, and mode says what values to put there (zeros by default). The original array is never modified. This page is for researchers and analysts who need to equalise signal lengths, add borders before a windowed or convolution step, or pad to a target shape, and who need to choose a mode deliberately because some modes change the statistics of the data.

What np.pad is used for in research

  • Equalising variable-length records (trials, time series, spectra) so they can be stacked into one 2-D array.
  • Adding borders to images or gridded data before a sliding-window operation, so output keeps the input size. For one-dimensional convolution, np.convolve has its own mode argument that handles the edges for you.
  • Padding to a required shape for a function or model that expects fixed dimensions.

All outputs below were produced by running the code on NumPy 2.5.1; the signature, modes and argument names are those of the NumPy 2.5 reference manual for numpy.pad, read 2026-11-07.

Install or access

np.pad ships with NumPy. Install from the official NumPy installation page (numpy.org/install): pip install numpy, or with conda conda install numpy. For an isolated environment: python -m venv my-env, activate it (source my-env/bin/activate on macOS and Linux, my-envScriptsactivate on Windows), then pip install numpy. Then import numpy as np (see import numpy as np if the import fails).

Step by step: pad an array

1. Choose pad_width

The manual lists these accepted forms of pad_width:

Form Meaning
((b1, a1), (b2, a2), ...) before and after counts for each axis
(before, after) or ((before, after),) the same before and after counts for every axis
(pad,) or pad (an int) the same count before and after, on every axis
{axis: int or (before, after)} pad only the named axes; negative axis keys such as {-1: 2} are allowed

2. Pad a 1-D array

import numpy as np a = np.array([1, 2, 3, 4, 5]) np.pad(a, (2, 3))                                      # [0 0 1 2 3 4 5 0 0 0] np.pad(a, (2, 3), 'constant', constant_values=(4, 6))  # [4 4 1 2 3 4 5 6 6 6]

3. Pad one axis of a 2-D array

x = np.array([[1, 2, 3], [4, 5, 6]]) np.pad(x, {1: (1, 2)}) # [[0 1 2 3 0 0] #  [0 4 5 6 0 0]] np.pad(x, ((1, 1), (2, 2)), 'edge') # [[1 1 1 2 3 3 3] #  [1 1 1 2 3 3 3] #  [4 4 4 5 6 6 6] #  [4 4 4 5 6 6 6]]

4. Pad to a target shape

np.pad takes amounts to add, not a final size, so compute the difference first. This recipe adds the whole shortfall after the data:

img = np.arange(1, 10).reshape(3, 3) target = (5, 4) pw = [(0, target[i] - img.shape[i]) for i in range(2)]   # [(0, 2), (0, 1)] padded = np.pad(img, pw)                                  # shape (5, 4)

To centre the data instead, use before = diff // 2 and after = diff - before. The result is identical to creating an array of the target shape with np.zeros and assigning the data into a slice (checked: c = np.zeros(target, dtype=img.dtype); c[:3, :3] = img gives an equal array), but np.pad also supports the non-zero modes.

5. Pad variable-length signals to one length

sigs = [np.array([1., 2, 3]), np.array([4., 5, 6, 7, 8]), np.array([9., 10])] L = max(len(s) for s in sigs) batch = np.stack([np.pad(s, (0, L - len(s)), constant_values=np.nan) for s in sigs]) np.nanmean(batch, axis=1)    # [2.  6.  9.5]

Padding with np.nan keeps the padding out of the statistics when you use the nan-aware functions (see NumPy NaN). Padding with the default zeros would have pulled each mean down.

Output and how to read it

The result has the same number of dimensions as the input; each axis grows by before + after. The data sit in the middle, unchanged. For arrays with more than one axis, NumPy documents that padding of later axes is partly computed from the already-padded earlier axes, so corner values come from the first axis’s padded values.

Which mode? Same input, every mode

Input a = [1, 2, 3, 4, 5], call np.pad(a, (2, 3), mode) (stat_length left at its default, the whole axis). Output run on NumPy 2.5.1:

mode result What the padded values are
constant (default) [0 0 1 2 3 4 5 0 0 0] constant_values, default 0
edge [1 1 1 2 3 4 5 5 5 5] the edge value of the axis
linear_ramp [0 0 1 2 3 4 5 3 1 0] linear ramp from the edge to end_values (default 0)
maximum [5 5 1 2 3 4 5 5 5 5] maximum of the vector (or of stat_length values at the edge)
mean [3 3 1 2 3 4 5 3 3 3] mean of the vector
median [3 3 1 2 3 4 5 3 3 3] median of the vector
minimum [1 1 1 2 3 4 5 1 1 1] minimum of the vector
reflect [3 2 1 2 3 4 5 4 3 2] mirror image, edge value not repeated
symmetric [2 1 1 2 3 4 5 5 4 3] mirror image, edge value repeated
wrap [4 5 1 2 3 4 5 1 2 3] the array treated as periodic
empty (undefined) uninitialised values; overwrite them before use

Reading the table for analysis: mean, median, maximum and minimum inject values derived from your data, so they change counts, variances and any statistic computed afterwards on the padded array. reflect versus symmetric differ only in whether the edge element is repeated. reflect_type='odd' (for reflect and symmetric) extends the signal with its odd reflection: reflect gives [-1 0 1 2 3 4 5 6 7 8] and symmetric gives [0 1 1 2 3 4 5 5 6 7]. A wrap pad is only appropriate when the data really are periodic.

Custom padding with a function

Instead of a mode string you can pass a function with the signature padding_func(vector, iaxis_pad_width, iaxis, kwargs). It receives each 1-D vector already zero-padded and modifies it in place; the padded regions are vector[:iaxis_pad_width[0]] and vector[-iaxis_pad_width[1]:]. Extra keyword arguments to np.pad arrive in kwargs.

Troubleshooting

  • ValueError: index can’t contain negative values. np.pad cannot crop: a negative amount in pad_width raises this error (seen on NumPy 2.5.1 with np.pad(s, -1)). To remove elements, use slicing.
  • ValueError: cannot convert float NaN to integer. Padding an integer array with constant_values=np.nan fails because the output keeps the input dtype. Convert first with .astype(float).
  • Silent truncation of fill values. Because the dtype is kept, np.pad(np.array([1, 2, 3]), 1, constant_values=2.7) returns [2 1 2 3 2]; the 2.7 became 2. Cast to float before padding when the fill value is fractional.
  • Result is the wrong size. pad_width is an amount added, not a target size; subtract the current shape as in step 4.
  • Padded the wrong axis. A bare (2, 3) is applied to every axis. Use the dict form or a per-axis tuple of pairs.
  • Shape mismatches afterwards in later operations are usually a broadcasting issue rather than a padding one; print .shape before and after.

Free alternatives and related tools

Need Option Note
Zero-filled array of a final size, then fill np.zeros plus slice assignment Same result as constant padding with zeros (checked above)
Array of a final size filled with one value np.full plus slice assignment Fill value other than 0
Smoothing or filtering with edge handling np.convolve modes Edge handling is built in, no manual padding
Remove or trim elements Slicing np.pad cannot use negative widths

For the sum or mean of a padded array, see NumPy sum and its NaN handling.

FAQ

How do I pad a NumPy array to a specific size?

Compute target - current for each axis, split it into before and after counts, and pass those as pad_width (step 4 above). np.pad adds amounts; it does not take a final shape.

How do I use numpy pad in Python?

Call np.pad(array, pad_width, mode='constant') after import numpy as np. With no mode it pads with zeros.

Does np.pad change the original array?

No. It returns a new ndarray with the same number of dimensions and a larger shape.

What is the difference between np.pad and np.zeros?

np.zeros creates a new array of a given shape filled with zeros. np.pad grows an existing array and can fill the border with zeros or with other modes such as edge, reflect or mean.

Sources

  • NumPy Manual (v2.5), numpy.pad: numpy.org/doc/stable/reference/generated/numpy.pad.html, read 2026-11-07.
  • NumPy, Installing NumPy: numpy.org/install, read 2026-11-07.
  • Example outputs and error messages: run by the author on NumPy 2.5.1, 2026-11-07.

Follow CASRAI

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

Ask CASRAI · free to try

Ask about NumPy pad (np.pad): Syntax, Modes and Examples

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

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 free 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 →