piRSquared - 1 year ago 80
Python Question

# find max per column of values that come before the min

consider the array

`a`

``````a = np.array([
[5, 4],
[4, 5],
[2, 2],
[6, 1],
[3, 7]
])
``````

I can find where the minimums are with

``````a.argmin(0)

array([2, 3])
``````

How do I find the maximum for column 0 of values before index 2. And the same for column 1 and index 3. And more importantly, where they are?

If I do

``````a.max(0)

array([6, 7])
``````

but I need

``````# max values
array([5, 5])

# argmax before mins
array([0, 1])
``````

Here's one approach using `broadcasting` -

``````b = np.where(a.argmin(0) >= np.arange(a.shape[0])[:,None],a,np.nan)
idx = np.nanargmax(b,axis=0)
out = a[idx,np.arange(a.shape[1])]
``````

Sample run -

``````In [38]: a
Out[38]:
array([[5, 4],
[4, 5],
[2, 2],
[6, 1],
[3, 7]])

In [39]: b = np.where(a.argmin(0) >= np.arange(a.shape[0])[:,None],a,np.nan)
...: idx = np.nanargmax(b,axis=0)
...: out = a[idx,np.arange(a.shape[1])]
...:

In [40]: idx
Out[40]: array([0, 1])

In [41]: out
Out[41]: array([5, 5])
``````

Alternatively, if `a` has positive numbers only, we could get `idx` simply by multiplying with the mask and using `argmax` : `(a*mask).argmax(0)`.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download