Home > OS >  How to get the rank of one numpy array based on intervals from another array?
How to get the rank of one numpy array based on intervals from another array?

Time:12-24

I have two numpy arrays:

arr = np.array([10,80,10,20,60,50,80,100])
intervals = np.array([20,35,60,100]) # this is always increasing


# we can get ranks from intervals
ranks = np.arange(len(intervals))   1 # array([1, 2, 3, 4])

Here, if the values is less than 20, it has rank 1, if 20<x<=35 rank2 and so on.

How to get the following answer? Either the dictionary or the array is fine.

required_answer_dict = {10:1, # <= 20
            80:4, # <=100
            10:1, # <= 20
            20:1, # <=20
            60:3, # <=60
            50:3, # <=60
            80:4, # <=100
            100:4 # <=100
           }

required_answer = [1,4,1,1,3,3,4,4]

CodePudding user response:

You can use np.digitize for this:

binned = np.digitize(arr - 1, intervals)   1
ans_dict = dict(zip(arr, binned))

Output:

>>> ans_dict
{
    10: 1,
    80: 4,
    20: 1,
    60: 3,
    50: 3,
    100: 4
}

CodePudding user response:

Reshape into a long format and compare each element to the intervals. The argmax() will return the values you are looking for.

import numpy as np
arr = np.array([10,80,10,20,60,50,80,100])
intervals = np.array([20,35,60,100]) # this is always increasing

(arr.reshape(-1,1) < intervals).argmax(axis=1) 1

Output

array([1, 4, 1, 2, 4, 3, 4, 1], dtype=int64)
  • Related