Trim / strip zeros of a numpy array
Use numpy.trim_zeros
:
>>> import numpy as np
>>> a = np.array([0,0,0,3,2,-1,0,0,7,9,13,0,0,0,0,0,0,0])
>>> np.trim_zeros(a)
array([ 3, 2, -1, 0, 0, 7, 9, 13])
To trim 2d arrays:
def trim_zeros_2D(array, axis=1):
mask = ~(array==0).all(axis=axis)
inv_mask = mask[::-1]
start_idx = np.argmax(mask == True)
end_idx = len(inv_mask) - np.argmax(inv_mask == True)
if axis:
return array[start_idx:end_idx,:]
else:
return array[:, start_idx:end_idx]