How to remove leading / trailing zeros from a NumPy array? Trim_zeros works only for 1D.
Here's some code that will handle 2-D arrays.
import numpy as np
# Arbitrary array
arr = np.array([
[0, 0, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 1, 1, 1, 0],
[0, 1, 0, 1, 0],
[1, 1, 0, 1, 0],
[1, 0, 0, 1, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
])
nz = np.nonzero(arr) # Indices of all nonzero elements
arr_trimmed = arr[nz[0].min():nz[0].max()+1,
nz[1].min():nz[1].max()+1]
assert np.array_equal(arr_trimmed, [
[0, 0, 0, 1],
[0, 1, 1, 1],
[0, 1, 0, 1],
[1, 1, 0, 1],
[1, 0, 0, 1],
])
This can be generalized to N-dimensions as follows:
def trim_zeros(arr):
"""Returns a trimmed view of an n-D array excluding any outer
regions which contain only zeros.
"""
slices = tuple(slice(idx.min(), idx.max() + 1) for idx in np.nonzero(arr))
return arr[slices]
test = np.zeros((5,5,5,5))
test[1:3,1:3,1:3,1:3] = 1
trimmed_array = trim_zeros(test)
assert trimmed_array.shape == (2, 2, 2, 2)
assert trimmed_array.sum() == 2**4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With