2

I have a numpy array as below:

a= array([[2, 3],
   [0, 2]])

and want to compare "vectors" in each row with every other rows, using np.greater, so to have:

array([[False, False],  <--- [2,3] compared with [2,3]
     [True, True]],     <--- [2,3] compared with [0,2]
     [[False, False],   <--- [0,2] compared with [2,3] 
     [False, False]])   <--- [0,2] compared with [0,2]

But if I try r=(np.greater.outer(a,a)) it compares every number in a with every other number in a, so to have:

array([[[[False, False],  <--- 2 compared with a
     [ True, False]],     

    [[ True, False],      <--- 3 compared with a
     [ True,  True]]],


   [[[False, False],      <--- 0 compared with a
     [False, False]],

    [[False, False],      <--- 2 compared with a 
     [ True, False]]]], dtype=bool)

¿How can I make an outer comparison row wise instead of element wise?

J. Torrecilla
  • 46
  • 1
  • 7

1 Answers1

4

Try this:

a[:,np.newaxis] > a

It is the same as this more explicit code:

a[:,np.newaxis,:] > a[np.newaxis,:,:]

Hat tip to https://stackoverflow.com/a/16500609/4323

Details on what it does: The use of Python numpy.newaxis

John Zwinck
  • 239,568
  • 38
  • 324
  • 436