Get N maximum values and indices along an axis in a NumPy array

后端 未结 3 1770
谎友^
谎友^ 2020-12-11 10:44

I think this is an easy question for experienced numpy users.

I have a score matrix. The raw index corresponds to samples and column index corresponds to items. For

3条回答
  •  一整个雨季
    2020-12-11 11:19

    In case someone is interested in the both the values and corresponding indices without tempering with the order, the following simple approach will be helpful. Though it could be computationally expensive if working with large data since we are using a list to store tuples of value, index.

    import numpy as np
    values = np.array([0.01,0.6, 0.4, 0.0, 0.1,0.7, 0.12]) # a simple array
    values_indices = [] # define an empty list to store values and indices
    while values.shape[0]>1:
        values_indices.append((values.max(), values.argmax()))
        # remove the maximum value from the array:
        values = np.delete(values, values.argmax())
    

    The final output as list of tuples:

    values_indices
    [(0.7, 5), (0.6, 1), (0.4, 1), (0.12, 3), (0.1, 2), (0.01, 0)]
    

提交回复
热议问题