1

I wanted to find the max of 2D array along the axis=0 and I don't want to include the value at the row-index. I'm not happy with this solution because I need to run this on a million of rows and I don't want to use for-loop here. I tried numpy.argmax but it calculates the max value of the row including the value at the row index.

My 2D Array

Arry=([[1,   0.5, 0.3,   0,    0.2],
       [0,   1,   0.2,   0.8,  0],
       [0,   1,   1,     0.3,  0],
       [0,   0,   0,     1,    0]])

Expected Output

[1, 3, 1]

The first row [1, 0.5, 0.3, 0, 0.2] has max value at index 1 i.e. 0.5 since value 1 is at row index 0, Similarly in the second row max value is 0.8 i.e. index 3 and the 4th row doesn't have any max value since all are zero

My Code

import numpy as np

for idx,subarry in enumerate(Arry):
    newlist=np.delete(subarry, idx)
    idx_min=min(np.where(subarry==np.max(newlist))[0])
    if idx_min != 0: min_elem_idx.append(idx_min)

print(min_elem_idx)
[1, 3, 1]

I am looking for a Pythonic way to achieve this without using the for loop

1 Answer 1

3

This should do the trick:

a = np.array([[1,   0.5, 0.3,   0,    0.2],
              [0,   1,   0.2,   0.8,  0],
              [0,   1,   1,     0.3,  0],
              [0,   0,   0,     1,    0]])

# Create an array of ones the same size as a
b = np.ones_like(a)

# Fill the diagonal of b with NaN
np.fill_diagonal(b, np.nan)

# Multiply the arrays in order to remove the index column from the max
c = a*b

# Find the index of the max value of every row (excluding the index value)
np.nanargmax(c, axis=1)

Output:

array([1, 3, 1, 0])

In order to filter out cases where every value is zero (and therefore "doesn't have a max," as you define it), you would have to do some additional work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.