Home > other >  Python, how to find the column index of the lowest element greater than a specified value in a numpy
Python, how to find the column index of the lowest element greater than a specified value in a numpy

Time:05-04

So I have a 2D numpy array. Let's say I have a random number e.g. x=46 and I want to find the column index of the lowest number greater than than 46.

a = np.array([[16,32,49,80,85],[2,57,59,70,77],[9,11,30,36,64]])

The value to this would then be 49 so answer would be column 2.

output = 2

CodePudding user response:

use np.where

Example:

a = np.array([[15, 8, 12], [11, 7, 3]])
np.where(a > 10) # (array([0, 0, 1]), array([0, 2, 0]))
# (0,0)=15 / (0,2)=12 / (1,0)=11

CodePudding user response:

import numpy as np

value = np.where(a > 46, a, 100000000000000).min()
index = (np.where(a == value)[1])[0]
print('value', value)
print('index', index )

Output

value 49
index 2

The condition greater than 46 is used here, everything that is less turns into a large value. The minimum number is found. According to this number, the index of the second dimension is obtained. [0] is used to extract a number.

Instead of a large number, it is better to use 'numpy.inf'. Thanks for the reminder Mechanic Pig.

CodePudding user response:

best_num = float("inf")
best_clm = None
for row in a:
    for clm, clm_val in enumerate(row):
        if clm_val < 46 and clm_val < best_num:
            best_num = clm_val
            best_clm = clm
print(best_clm)

something like this (you can change 46 to whatever you want)

CodePudding user response:

Using numpy.ma.masked_array is probably the most elegant way:

>>> a = np.array([[16,32,49,80,85],[2,57,59,70,77],[9,11,30,36,64]])
>>> np.ma.masked_array(a, a < 46)
masked_array(
  data=[[--, --, 49, 80, 85],
        [--, 57, 59, 70, 77],
        [--, --, --, --, 64]],
  mask=[[ True,  True, False, False, False],
        [ True, False, False, False, False],
        [ True,  True,  True,  True, False]],
  fill_value=999999)
>>> np.ma.masked_array(a, a < 46).argmin() % a.shape[1]
2

I modulo the result of a.shape[1] to get the exact number of columns, because argmin returns the position of the minimum value in the flattened array.

  • Related