Search code examples
pythondata-partitioning

Finding where a given number falls in a partition


Suppose I have a sorted array of integers say

partition = [0, 3, 7, 12, 18, 23, 27]

and then given a value

value = 9

I would like to return the interval on which my value sits. For example

bounds = function(partition, value)
print(bounds)
>>>[7,12]

Is there a function out there that might be able to help me or do I have to build this from scratch?


Solution

  • Try numpy.searchsorted(). From the documentary:

    Find indices where elements should be inserted to maintain order.

    import numpy as np
    partition = np.array( [0, 3, 7, 12, 18, 23, 27] )
    value = 9
    idx = np.searchsorted(partition,value)
    bound = (partition[idx-1],partition[idx])
    print(bound)
    >>>>(7,12)
    

    The advantage of searchsorted is that it can give you the index for multiple values at once.