Search code examples
julia

Julia: Construct an array from an index array and an array to choose from (or: What is the Julia equivalent of np.choose in numpy?)


In Python (Numpy) there is a np.choose function, that constructs an array from an index array and a list of arrays to choose from.

Simple example (and I am actually mostly interested in this simple version of the problem with a 1D choice-array):

import numpy as np
idx_arr = np.array([0, 1, 2, 1, 3])
choices = np.array([0, 10, 20, 30])
new_arr = np.choose(idx_arr, choices)  # array([ 0, 10, 20, 10, 30])

For the example above the same result can be created in Julia using a for-loop using list comprehension

idx_arr = [1, 2, 3, 2, 4];
choices = [0, 10, 20, 30];
new_arr = [choices[idx_arr[i]] for i in 1:length(idx_arr)];

Is there a Julia equivalent for np.choose or any other way to achieve this that does not require looping over the index array?


Solution

  • choices[idx_arr] will work (note that indices are 1-based not 0-based).

    The example in the question:

    julia> idx_arr = [1, 2, 3, 2, 4];
    
    julia> choices = [0, 10, 20, 30];
    
    julia> new_arr = [choices[idx_arr[i]] for i in 1:length(idx_arr)]
    5-element Vector{Int64}:
      0
     10
     20
     10
     30
    
    julia> choices[idx_arr]
    5-element Vector{Int64}:
      0
     10
     20
     10
     30