BorkoP
BorkoP

Reputation: 330

Numpy function that rounds to specified integer to specified range

Lets say I have an array y which contains continuos numbers which mostly go from -1 to 5 with probably some outliers but I want to fix them to specified integers(0,1,2,3,4) by giving them specific points where the ranges of integers end ie. [0.7,1.6,2.4,3.7] so here 0 would be everything below 0.7, 1 would be everything between 0.7 and 1.6, 2 would be between 1.6 and 2.4 etc. I'm wondering if there's a function in numpy that can do this for me more efficiently than the code below. I've read the docs of numpy.fix and numpy.rint but I dont see how i can do that with them.

Here's an example of what I want to do basically:

def flatten(y):
            for i in range(len(y)):
                if y[i] <0.7:
                    y[i] = 0
                elif y[i]>0.7 and y[i]<1.6:
                    y[i] = 1
                elif y[i]>1.6 and y[i]< 2.4:
                    y[i] = 2
                elif y[i] >2.4 and y[i]<3.7:
                    y[i] = 3
                elif y[i]> 3.7:
                    y[i] = 4
            return y

Doesn't have to be a single function but at least something more efficient than this.

Upvotes: 0

Views: 44

Answers (1)

Nils Werner
Nils Werner

Reputation: 36765

You can use np.digitize:

 np.digitize(y, [0.7, 1.6, 2.4, 3.7])

Upvotes: 1

Related Questions