[Numpy-discussion] trim_zeros in more than one dimension?

Keith Goodman kwgoodman@gmail....
Tue Apr 20 10:32:12 CDT 2010

On Tue, Apr 20, 2010 at 6:03 AM, Andreas Hilboll <lists@hilboll.de> wrote:
> Hi there,
> is there an easy way to do something like trim_zeros() does, but for a
> n-dimensional array? I have a 2d array with only zeros in the first and
> last rows and columns, and would like to trim this array to only the
> non-zero part ...
> Thanks,
> Andreas.

I have some code that does something similar for NaNs.

Create an array:

>> x = np.arange(12, dtype=float).reshape(3,4)
>> x[[0,-1],:] = np.nan
>> x[:,[0,-1]] = np.nan
>> x
array([[ NaN,  NaN,  NaN,  NaN],
       [ NaN,   5.,   6.,  NaN],
       [ NaN,  NaN,  NaN,  NaN]])

Use the la package to convert the array to a labeled array:

>> y = la.larry(x)

Then remove all rows and columns that contain only NaN:

>> y.vacuum().A
   array([[ 5.,  6.]])


>> y.vacuum().squeeze().A
   array([ 5.,  6.])

It should work for arbitrary number of dimensions.

The code (Simplified BSD License) is here:


More information about the NumPy-Discussion mailing list