Numpy trim_zeros in 2D or 3D
问题 How to remove leading / trailing zeros from a NumPy array? Trim_zeros works only for 1D. 回答1: The following function works for any dimension: def trim_zeros(arr, margin=0): ''' Trim the leading and trailing zeros from a N-D array. :param arr: numpy array :param margin: how many zeros to leave as a margin :returns: trimmed array :returns: slice object ''' s = [] for dim in range(arr.ndim): start = 0 end = -1 slice_ = [slice(None)]*arr.ndim go = True while go: slice_[dim] = start go = not np