Select One Element in Each Row of a Numpy Array by Column Indices -
is there better way "output_array" "input_array" , "select_id" ?
can rid of range( input_array.shape[0] )
?
>>> input_array = numpy.array( [ [3,14], [12, 5], [75, 50] ] ) >>> select_id = [0, 1, 1] >>> print input_array [[ 3 14] [12 5] [75 50]] >>> output_array = input_array[ range( input_array.shape[0] ), select_id ] >>> print output_array [ 3 5 50]
you can choose given array using numpy.choose
constructs array index array (in case select_id
) , set of arrays (in case input_array
) choose from. may first need transpose input_array
match dimensions. following shows small example:
in [101]: input_array out[101]: array([[ 3, 14], [12, 5], [75, 50]]) in [102]: input_array.shape out[102]: (3, 2) in [103]: select_id out[103]: [0, 1, 1] in [104]: output_array = np.choose(select_id, input_array.t) in [105]: output_array out[105]: array([ 3, 5, 50])
Comments
Post a Comment