0

I want to trim a 1D numpy array by removing all elements from left and right that are a certain value (e.g. 255). It seems a bit silly to do all the extra work of

np.trim_zeros(arr - 255) + 255

Is there an equivalent trim function which allows you to specify the values that trigger removal? Or can I perhaps roll my own by looking at the internals of trim_zeros?

user2667066
  • 1,867
  • 2
  • 19
  • 30
  • `np.trim_zeros` is Python code, and fairly obvious. Read it and write your own. – hpaulj Jun 19 '19 at 21:33
  • See this answer: https://stackoverflow.com/a/55864896/1161132. Not sure internally how where is implemented so it may want to look into performance. – bgura Jun 19 '19 at 21:37
  • `trim_zeros` does 2 things. 1) find the slice we want to keep (the bounds of the nonzero block), 2) return that slice. – hpaulj Jun 20 '19 at 04:10
  • @hpaulj - thanks. Silly me - I didn't see it was a python function, just assumed it was in C. – user2667066 Jun 20 '19 at 06:03

1 Answers1

0

@hpaulj pointed out that the code for trim_zeros is written in python and very simple to modify. So the following code will work fine, and should be as fast as the built in trim_zeros.

def trim(filt, trim_value=0., trim='fb'):
    """
    Copied from np.trim_zeros, but allows the trim value to be specified
    """
    first = 0
    trim = trim.upper()
    if 'F' in trim:
        for i in filt:
            if i != trim_value:
                break
            else:
                first = first + 1
    last = len(filt)
    if 'B' in trim:
        for i in filt[::-1]:
            if i != trim_value:
                break
            else:
                last = last - 1
    return filt[first:last]

It might be nice to add this to the numpy codebase, I guess.

user2667066
  • 1,867
  • 2
  • 19
  • 30