Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get second minimum values per column in 2D array

How can I get the second minimum value from each column? I have this array:

A = [[72 76 44 62 81 31]
     [54 36 82 71 40 45]
     [63 59 84 36 34 51]
     [58 53 59 22 77 64]
     [35 77 60 76 57 44]]

I wish to have output like:

A = [54 53 59 36 40 44]
like image 359
Mr Dan Avatar asked Mar 11 '20 12:03

Mr Dan


People also ask

How do you find the smallest number in a 2D array in Python?

min to return the minimum value, or equivalently for an array arrname use arrname. min() . As you mentioned, numpy. argmin returns the index of the minimum value (of course, you can then use this index to return the minimum value by indexing your array with it).

How do you find the minimum value of a 2D array?

You can easily find the index of the max value in a 1-dimensional NumPy array. But for the 2D array, you have to use Numpy module unravel_index. It will easily find the Index of the Max and Min value.

How do you find the max and min value of a 2D array in Python?

We can find the minimum and maximum values from the each row of a 2D numpy array by using the "min" and "max" functions available in the Numpy library.


1 Answers

Try this, in just one line:

[sorted(i)[1] for i in zip(*A)]

in action:

In [12]: A = [[72, 76, 44, 62, 81, 31], 
    ...:      [54 ,36 ,82 ,71 ,40, 45], 
    ...:      [63 ,59, 84, 36, 34 ,51], 
    ...:      [58, 53, 59, 22, 77 ,64], 
    ...:      [35 ,77, 60, 76, 57, 44]] 

In [18]: [sorted(i)[1] for i in zip(*A)]                                                                                                                                                                           
Out[18]: [54, 53, 59, 36, 40, 44]

zip(*A) will transpose your list of list so the columns become rows.

and if you have duplicate value, for example:

In [19]: A = [[72, 76, 44, 62, 81, 31], 
    ...:  [54 ,36 ,82 ,71 ,40, 45], 
    ...:  [63 ,59, 84, 36, 34 ,51], 
    ...:  [35, 53, 59, 22, 77 ,64],   # 35
    ...:  [35 ,77, 50, 76, 57, 44],]  # 35

If you need to skip both 35s, you can use set():

In [29]: [sorted(list(set(i)))[1] for i in zip(*A)]                                                                                                                                                                
Out[29]: [54, 53, 50, 36, 40, 44]
like image 172
Mehrdad Pedramfar Avatar answered Oct 24 '22 17:10

Mehrdad Pedramfar