Home > Mobile >  Finding the row in an numpy array that has the smallest values compared to all other rows
Finding the row in an numpy array that has the smallest values compared to all other rows

Time:09-26

say i have the following matrix:

A = [[7,5,1,2]
     [10,1,3,8]
     [2,2,2,3]]

I need to extract the row with elements closest to 0 compared to all other rows, aka the row with the minimal elements. So i need [2,2,2,3]

I have tried a number of things, np.min, np.amin, np.argmin

But all are giving me the minimum values of each row for example:

[2,1,1,2]

This is not what im looking for.

If someone knows the right function could you point me to the documentation of the function?

Thank you.

CodePudding user response:

The first way that comes to mind is to find the minimum of each row. Then find the argmin of that array.

row_mins = A.min(axis=0)
row_with_minimum = row_mins.argmin()

Then to get the row with the minimum element, do

A[row_with_minimum, :]

CodePudding user response:

import numpy as np

A = np.array([[7,5,1,2],
             [10,1,3,8],
             [2,2,2,3]])

print(print(A[np.argmin(A.sum(axis=1))]))

# [2 2 2 3]

CodePudding user response:

It depends on how you define distance when you say closest. I'm guessing you are looking for the Euclidean distance, i.e. L2 norm here. In which case, you can just find the minimum sum of square for all rows:

A[(A ** 2).sum(1).argmin()]
# array([2, 2, 2, 3])

You can also find the closest by L1 norm or the sum of absolute difference against 0s:

A[np.abs(A).sum(1).argmin()]
# array([2, 2, 2, 3])

In this dummy example, the two methods give the same result, but they could be different depending on the actual data.

  • Related