Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy trim_zeros in 2D or 3D

How to remove leading / trailing zeros from a NumPy array? Trim_zeros works only for 1D.

like image 530
alex Avatar asked Apr 30 '19 08:04

alex


1 Answers

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
like image 145
Bill Avatar answered Oct 03 '22 10:10

Bill