Skip to content

ENH: Extend numpy.pad to handle pad_width dictionary argument. #29273

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
ENH: Extend numpy.pad to handle pad_width dictionary argument.
  • Loading branch information
carlosgmartin committed Jun 26, 2025
commit 8f5ce9cbe49a8f4191455c70adca28f61cf774cf
1 change: 1 addition & 0 deletions doc/release/upcoming_changes/29273.new_feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Extend ``numpy.pad`` to accept a dictionary for the ``pad_width`` argument.
38 changes: 37 additions & 1 deletion numpy/lib/_arraypad_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
of an n-dimensional array.

"""
import typing

import numpy as np
from numpy._core.overrides import array_function_dispatch
from numpy.lib._index_tricks_impl import ndindex
Expand Down Expand Up @@ -550,14 +552,17 @@ def pad(array, pad_width, mode='constant', **kwargs):
----------
array : array_like of rank N
The array to pad.
pad_width : {sequence, array_like, int}
pad_width : {sequence, array_like, int, dict}
Number of values padded to the edges of each axis.
``((before_1, after_1), ... (before_N, after_N))`` unique pad widths
for each axis.
``(before, after)`` or ``((before, after),)`` yields same before
and after pad for each axis.
``(pad,)`` or ``int`` is a shortcut for before = after = pad width
for all axes.
If a ``dict``, each key is an axis and its corresponding value is an ``int`` or
``int`` pair describing the padding ``(before, after)`` or ``pad`` width for
that axis.
mode : str or function, optional
One of the following string values or a user supplied function.

Expand Down Expand Up @@ -745,8 +750,39 @@ def pad(array, pad_width, mode='constant', **kwargs):
[100, 100, 3, 4, 5, 100, 100],
[100, 100, 100, 100, 100, 100, 100],
[100, 100, 100, 100, 100, 100, 100]])

>>> a = np.arange(1, 7).reshape(2, 3)
>>> np.pad(a, {1: (1, 2)})
array([[0, 1, 2, 3, 0, 0],
[0, 4, 5, 6, 0, 0]])
>>> np.pad(a, {-1: 2})
array([[0, 0, 1, 2, 3, 0, 0],
[0, 0, 4, 5, 6, 0, 0]])
>>> np.pad(a, {0: (3, 0)})
array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[1, 2, 3],
[4, 5, 6]])
>>> np.pad(a, {0: (3, 0), 1: 2})
array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 2, 3, 0, 0],
[0, 0, 4, 5, 6, 0, 0]])
"""
array = np.asarray(array)
if isinstance(pad_width, dict):
seq = [(0, 0)] * array.ndim
for axis, width in pad_width.items():
match width:
case int(both):
seq[axis] = both, both
case tuple((int(before), int(after))):
seq[axis] = before, after
case _ as invalid:
typing.assert_never(invalid)
pad_width = seq
pad_width = np.asarray(pad_width)

if not pad_width.dtype.kind == 'i':
Expand Down
14 changes: 10 additions & 4 deletions numpy/lib/_arraypad_impl.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,17 @@ _ModeKind: TypeAlias = L[
# TODO: In practice each keyword argument is exclusive to one or more
# specific modes. Consider adding more overloads to express this in the future.

_PadWidth: TypeAlias = (
_ArrayLikeInt
| dict[int, int]
| dict[int, tuple[int, int]]
| dict[int, int | tuple[int, int]]
)
# Expand `**kwargs` into explicit keyword-only arguments
@overload
def pad(
array: _ArrayLike[_ScalarT],
pad_width: _ArrayLikeInt,
pad_width: _PadWidth,
mode: _ModeKind = ...,
*,
stat_length: _ArrayLikeInt | None = ...,
Expand All @@ -58,7 +64,7 @@ def pad(
@overload
def pad(
array: ArrayLike,
pad_width: _ArrayLikeInt,
pad_width: _PadWidth,
mode: _ModeKind = ...,
*,
stat_length: _ArrayLikeInt | None = ...,
Expand All @@ -69,14 +75,14 @@ def pad(
@overload
def pad(
array: _ArrayLike[_ScalarT],
pad_width: _ArrayLikeInt,
pad_width: _PadWidth,
mode: _ModeFunc,
**kwargs: Any,
) -> NDArray[_ScalarT]: ...
@overload
def pad(
array: ArrayLike,
pad_width: _ArrayLikeInt,
pad_width: _PadWidth,
mode: _ModeFunc,
**kwargs: Any,
) -> NDArray[Any]: ...
12 changes: 12 additions & 0 deletions numpy/lib/tests/test_arraypad.py
Original file line number Diff line number Diff line change
Expand Up @@ -1413,3 +1413,15 @@ def test_dtype_persistence(dtype, mode):
arr = np.zeros((3, 2, 1), dtype=dtype)
result = np.pad(arr, 1, mode=mode)
assert result.dtype == dtype


@pytest.mark.parametrize("input_shape, pad_width, expected_shape", [
((3, 4, 5), {-2: (1, 3)}, (3, 4 + 1 + 3, 5)),
((3, 4, 5), {0: (5, 2)}, (3 + 5 + 2, 4, 5)),
((3, 4, 5), {0: (5, 2), -1: (3, 4)}, (3 + 5 + 2, 4, 5 + 3 + 4)),
((3, 4, 5), {1: 5}, (3, 4 + 2 * 5, 5)),
])
def test_pad_dict_pad_width(input_shape, pad_width, expected_shape):
a = np.zeros(input_shape)
result = np.pad(a, pad_width)
assert result.shape == expected_shape
5 changes: 5 additions & 0 deletions numpy/typing/tests/data/reveal/arraypad.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,8 @@ assert_type(np.pad(AR_LIKE, (2, 3), "constant"), npt.NDArray[Any])

assert_type(np.pad(AR_f8, (2, 3), mode_func), npt.NDArray[np.float64])
assert_type(np.pad(AR_f8, (2, 3), mode_func, a=1, b=2), npt.NDArray[np.float64])

assert_type(np.pad(AR_i8, {-1: (2, 3)}), npt.NDArray[np.int64])
assert_type(np.pad(AR_i8, {-2: 4}), npt.NDArray[np.int64])
pad_width: dict[int, int | tuple[int, int]] = {-1: (2, 3), -2: 4}
assert_type(np.pad(AR_i8, pad_width), npt.NDArray[np.int64])
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy