[Numpy-discussion] trim_zeros in more than one dimension?
Bruce Southey
bsouthey@gmail....
Wed Apr 21 10:34:40 CDT 2010
On 04/21/2010 08:36 AM, Robert Kern wrote:
> On Tue, Apr 20, 2010 at 18:45, Charles R Harris
> <charlesr.harris@gmail.com> wrote:
>
>> On Tue, Apr 20, 2010 at 7: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 ...
>>>
>> I think for your application it would be easier to use a subarray, something
>> like a[1:-1, 1:-1].
>>
> Yes, but I think he's asking for a function that will find the
> appropriate slices for him, justl like trim_zeros() does for 1D
> arrays.
>
>
If the sum of axis to be removed equals zero then you can conditionally
remove that axis. For 2-d you can do:
import numpy as np
ba=np.array([[0,0,0], [1,2, 0], [3,4, 0], [0,0,0]])
ndx0=ba.sum(axis=0)>0 #indices of axis 0 where the sum is greater than zero
ac=ba[:,ndx0]
ndx1=ac.sum(axis=1)>0 #indices of axis 1 where the sum is greater than zero
ad=ac[ndx1,:]
>>> ba
array([[0, 0, 0],
[1, 2, 0],
[3, 4, 0],
[0, 0, 0]])
>>> ad
array([[1, 2],
[3, 4]])
If the sum of an dimension is also zero somewhere else in the array then
you need to correct the appropriate index first (which is why I created
a separate variable). Obviously higher dimensions are left untested.
Bruce
More information about the NumPy-Discussion
mailing list