1

I have a multidimensional numpy array consisting of tuples like below:

[[(0.56, 1),(0.25, 4), ...],[(0.11, 9), ...], ...]

The second element of each tuple is an index reference. I want to extract the tuple with the highest first value per row. Is there a way to achieve this with numpy max?

One thing I tried is playing around with the axis parameter like below:

np.max(my_array, axis=0)

But this shuffles around the pairs with the index reference not preserved. E.g. the first row in the above example would show something like [(0.56,4), ...] whereas I want it to show [(0.56,1), ...]

Layman
  • 797
  • 1
  • 7
  • 23
  • 1
    Is this helpfull? https://stackoverflow.com/questions/13145368/find-the-maximum-value-in-a-list-of-tuples-in-python – kabooya Mar 13 '21 at 11:07
  • @kabooya I was checking that earlier. I am looking for a solution specifically with numpy vs standard lib, but worth linking still – Layman Mar 13 '21 at 11:09
  • Don't use an numpy array of tuples. Convert it just into a numpy array where the last dimension is 2. – orlp Mar 13 '21 at 11:12
  • Is there any way you are using tuples instead of arrays? – kabooya Mar 13 '21 at 11:14
  • When it is converted to a numpy array those tuples are treated as lists. I specified the problem like this to convey the elements are pairs – Layman Mar 13 '21 at 11:15

3 Answers3

1

Don't use tuples in numpy arrays. Convert it all to a numpy array with the last dimension being 2:

>>> a = np.array([[(0.56, 1), (0.25, 4)],[(0.11, 9), (0.19, 5)]])
>>> a.shape
(2, 2, 2)

Then:

>>> highest_val_per_row = np.argmax(a[:,:,0], axis=1)
>>> a[np.arange(a.shape[0]), highest_val_per_row]
array([[0.56, 1.  ],
       [0.19, 5.  ]])
orlp
  • 112,504
  • 36
  • 218
  • 315
1

In plain python, you could use :

[max(row, key=lambda row: row[0]) for row in array]
ganto
  • 102
  • 7
0

You can try something linke this:

lst = [[(0.56, 1),(0.25, 4)],[(0.11, 9), (0.25, 4)]]

for e in lst: 
    print(max(e))

However, i think there are more efficient ways of doing it.

kabooya
  • 447
  • 3
  • 14