[Numpy-discussion] Getting index of array after applying cond

Robert Kern robert.kern at gmail.com
Fri Apr 2 11:37:23 EDT 2010


On Fri, Apr 2, 2010 at 09:31, Shailendra <shailendra.vikas at gmail.com> wrote:
> Hi All,
> I have a following model problem. Let i have a array
>>>> x
> array([[1, 2, 3, 4, 5],
>       [6, 7, 8, 7, 6],
>       [1, 2, 3, 4, 5]])
>
> suppose i apply some cond on it.
>>>> cond= x>5
>>>> x[cond]
> array([6, 7, 8, 7, 6])
>
> Now, i want to argmax on this
>>>> max=argmax(x[cond])
>>>> max
> 2
>>>> x[cond][max]
> 8
> Now , I want to get the index of this element in x. How to acheive
> this. In real situation x will be huge.

In [1]: x = array([[1,2,3,4,5], [6,7,8,7,6], [1,2,3,4,5]])

In [2]: x
Out[2]:
array([[1, 2, 3, 4, 5],
       [6, 7, 8, 7, 6],
       [1, 2, 3, 4, 5]])

In [3]: cond = (x > 5)

In [4]: i, j = where(cond)

In [5]: i
Out[5]: array([1, 1, 1, 1, 1])

In [6]: j
Out[6]: array([0, 1, 2, 3, 4])

In [7]: argmax(x[cond])
Out[7]: 2

In [8]: i[2], j[2]
Out[8]: (1, 2)

In [9]: x[i[2], j[2]]
Out[9]: 8

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the NumPy-Discussion mailing list