[Numpy-discussion] trim_zeros in more than one dimension?
Tue Apr 20 10:32:12 CDT 2010
On Tue, Apr 20, 2010 at 6:03 AM, Andreas Hilboll <firstname.lastname@example.org> 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 ...
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
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:
array([[ 5., 6.]])
array([ 5., 6.])
It should work for arbitrary number of dimensions.
The code (Simplified BSD License) is here:
More information about the NumPy-Discussion