0

I'm trying to perform this function on two 2D numpy arrays: Step 1: Find np.argmax(b, axis=1) indices. Step 2: Find b[indices] > a[indices] Step 3: Return value in a 2D Boolean array.

I tried this:

np.where((b>a)&np.argmax(b,axis=1).reshape((3,-1)), True, False)

but no dice. Any ideas?

Thanks in advance.

Noob Saibot
  • 4,573
  • 10
  • 36
  • 60
  • 1
    Should the boolean array have the same shape as `a` and `b` or should it be 1D with length `len(a)`? I'm having trouble understanding your desired output. – askewchan Mar 26 '13 at 22:46
  • Can you explain this a little more? "For the max value in a row in b, `b > a == True`. Otherwise, `False`." – YXD Mar 26 '13 at 22:47
  • @askewchan: Yes, the same shape. Sorry. – Noob Saibot Mar 26 '13 at 22:49
  • It's still not clear to me I'm afraid. I think it would be helpful here if you gave some expected input and output values. – YXD Mar 26 '13 at 22:50
  • @MrE: Think more the output of the `np.where` function, except that only `output[0,1]` is true, as `0.75183753` is both the maximum value of its row in `b`, AND it is greater than the corresponding value in a (i.e., `a[0,1`). Clearer? – Noob Saibot Mar 26 '13 at 22:53
  • @NoobSaibot I think my answer now does what you are after – YXD Mar 26 '13 at 23:04

1 Answers1

3

Based on your comments my best understanding is:

output = (np.max(b,axis=1)[...,None] == b) & (b > a)

Where we make use of Numpy broadcasting to do the "is the maximum of its row in b" part:

np.max(b,axis=1)[...,None] == b

Or perhaps clearer:

np.max(b,axis=1)[...,np.newaxis] == b
YXD
  • 31,741
  • 15
  • 75
  • 115
  • But could you please explain a bit more the "[...,None]" part? What sorcery is that? – Noob Saibot Mar 26 '13 at 23:09
  • Excellent, glad it helped! This is [a good overview](http://scipy-lectures.github.com/intro/numpy/numpy.html#broadcasting) of the broadcasting sorcery. [Here's my question](http://stackoverflow.com/questions/8299891/vectorization-of-this-numpy-double-loop) where I first learned about the broadcasting rules - [`np.newaxis` can/should be used instead of `None`](http://stackoverflow.com/questions/944863/numpy-should-i-use-newaxis-or-none). It's a very useful trick. – YXD Mar 26 '13 at 23:15