Home > Back-end >  Find element-wise index of min value across multiple 2d numpy arrays
Find element-wise index of min value across multiple 2d numpy arrays

Time:03-02

I have several arrays of the same shape and want to find a way to not just get the minimum value of each cell, but also the array from which the min value is coming from. I think the best way to do this is by using an n-dimensional array to store each 2-d array so that I can return the index of the min value for each cell. For example, let's say I have 3 arrays:

>>> import numpy as np
>>> a = np.random.random((3,3))
>>> b = np.random.random((3,3))
>>> c= np.random.random((3,3))
>>> arr = (a, b,c)
>>> print(arr[0])
[[0.29242554 0.408617   0.79015308]
 [0.52468204 0.36527803 0.51636725]
 [0.21796501 0.5780124  0.96879438]]
>>> print(arr[1])
[[0.48522564 0.24768296 0.22151351]
 [0.04493776 0.82884756 0.89689985]
 [0.30159678 0.47734114 0.47589837]]
>>> print(arr[2])
[[0.91569256 0.81359633 0.2493089 ]
 [0.97324684 0.09040656 0.20129747]
 [0.89355251 0.08643836 0.44796705]]

From this, I can return an array that has the min value across all 2d arrays:

np.minimum.reduce(arr)
array([[0.29242554, 0.24768296, 0.22151351],
       [0.04493776, 0.09040656, 0.20129747],
       [0.21796501, 0.08643836, 0.44796705]])

But how do I get the indices of these values so I can apply it to another set of arrays that are the same shape and size?:

CodePudding user response:

Put a, b and c into a single array, and use the min() and argmin() methods with axis=0.

Here's an example with smaller arrays:

In [218]: a = np.array([[2.0, 3.0], [5.0, 7.0]])

In [219]: b = np.array([[1.5, 9.0], [4.5, 6.0]])

In [220]: c = np.array([[3.0, 6.5], [5.0, 5.0]])

Put them into a single array with shape (3, 2, 2):

In [221]: arr = np.array((a, b, c))

In [222]: arr.shape
Out[222]: (3, 2, 2)

Use the min() and argmin() methods to get the minimum value and its index:

In [223]: arr.min(axis=0)
Out[223]: 
array([[1.5, 3. ],
       [4.5, 5. ]])

In [224]: arr.argmin(axis=0)
Out[224]: 
array([[1, 0],
       [1, 2]])
  • Related