Search code examples
juliabins

What is the alternate of numpy.digitize() function in Julia?


I would like to know, how may I replicate the numpy.digitize() functionality in julia? I am trying to convert this python example to Julia.

Python Example

x = np.array([0.2, 6.4, 3.0, 1.6])
bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0])
inds = np.digitize(x, bins)

Output: array([1, 4, 3, 2], dtype=int64)

I tried using searchsorted function in Julia but it doesn't replicate the output form python. Please suggest a solution to this problem.

Thanks in advance!!


Solution

  • You may use searchsortedlast with broadcasting:

    julia> x = [0.2, 6.4, 3.0, 1.6]
    4-element Array{Float64,1}:
     0.2
     6.4
     3.0
     1.6
    
    julia> bins = [0.0, 1.0, 2.5, 4.0, 10.0]
    5-element Array{Float64,1}:
      0.0
      1.0
      2.5
      4.0
     10.0
    
    julia> searchsortedlast.(Ref(bins), x)
    4-element Array{Int64,1}:
     1
     4
     3
     2