Skip to content

Commit 571348e

Browse files
committed
MAINT: Honor trim order
In case the user passes in an all-zero array and string to `trim` that starts with "b", the last dimension should be sliced first. In all other cases the first dimension takes precedence.
1 parent 935b1c8 commit 571348e

File tree

1 file changed

+19
-18
lines changed

1 file changed

+19
-18
lines changed

numpy/lib/function_base.py

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1607,6 +1607,10 @@ def trim_zeros(
16071607
returned. It contains the number of trimmed samples in each dimension
16081608
at the front and back.
16091609
1610+
Notes
1611+
-----
1612+
For all-zero arrays, the first axis is trimmed first.
1613+
16101614
Examples
16111615
--------
16121616
>>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0))
@@ -1625,6 +1629,12 @@ def trim_zeros(
16251629
trim = trim.lower()
16261630

16271631
absolutes = np.abs(filt)
1632+
if atol > 0:
1633+
absolutes[absolutes <= atol] = 0
1634+
if rtol > 0:
1635+
absolutes[absolutes <= rtol * absolutes.max()] = 0
1636+
nonzero = np.nonzero(absolutes)
1637+
16281638
lengths = np.zeros((absolutes.ndim, 2), dtype=np.intp)
16291639

16301640
if axis is None:
@@ -1635,28 +1645,19 @@ def trim_zeros(
16351645
if axis.ndim == 0:
16361646
axis = np.asarray([axis], dtype=np.intp)
16371647

1638-
if atol > 0:
1639-
absolutes[absolutes <= atol] = 0
1640-
if rtol > 0:
1641-
absolutes[absolutes <= rtol * absolutes.max()] = 0
1642-
1643-
nonzero = np.nonzero(absolutes)
1644-
16451648
for current_axis in axis:
1646-
absolutes.take([], current_axis) # Raises if axis is out of bounds
1647-
if current_axis < 0:
1648-
current_axis += absolutes.ndim
1649+
current_axis = normalize_axis_index(current_axis, absolutes.ndim)
16491650

16501651
if nonzero[current_axis].size > 0:
16511652
start = nonzero[current_axis].min()
1652-
stop = nonzero[current_axis].max()
1653-
stop += 1
1653+
stop = nonzero[current_axis].max() + 1
16541654
else:
1655-
# In case the input is all-zero, slice only in front
1656-
start = stop = absolutes.shape[current_axis]
1657-
if "f" not in trim:
1658-
# except when only the backside is to be sliced
1659-
stop = 0
1655+
# In case the input is all-zero, slice depending on preference
1656+
# given by user
1657+
if trim.startswith("b"):
1658+
start = stop = 0
1659+
else:
1660+
start = stop = absolutes.shape[current_axis]
16601661

16611662
# Only slice on specified side(s)
16621663
if "f" not in trim:
@@ -1665,7 +1666,7 @@ def trim_zeros(
16651666
stop = None
16661667

16671668
# Use multi-dimensional slicing only when necessary, this allows
1668-
# preservation of the non-arrays input types
1669+
# preservation of the non-array input types
16691670
sl = slice(start, stop)
16701671
if current_axis != 0:
16711672
sl = (slice(None),) * current_axis + (sl,) + (...,)

0 commit comments

Comments
 (0)