How to do ordered comparisons like `<` on structured numpy arrays?

Viewed 40

In a structured array that has some dtype tuple, it seems you can sort and do == but not operations like < for lexicographic ordering.

For example, say I have an array of tuples:

A = np.array([(3, 2),
              (1, 8),
              (5, 1),
              (3, 1),
              (4, 7)],
             dtype='i8,i8')

Calling sort works as expected, lexicographic ordering of the tuples:

>>> np.sort(A)
array([(3, 1), (3, 2), (4, 7), (5, 1), (6, 8)],
      dtype=[('f0', '<i8'), ('f1', '<i8')])

And it's even possible to do vectorized equality/inequality comparison:

>>> x = A[3]
>>> A != x
array([ True,  True,  True, False,  True])

But trying to do ordered comparisons like <, <=, >= raises

>>> A < x
TypeError: '>' not supported between instances of 'numpy.ndarray' and 'numpy.ndarray'

The best solution I have so far is to "manually" implement lexicographic ordering columnwise, but this technique doesn't extend easily to higher tuple dimensions and just feels like the "wrong way":

>>> (A['f0'] < x[0]) | ((A['f0'] == x[0]) & (A['f1'] < x[1]))
array([False,  True, False, False, False])

(My actual problem is that I have a very large array of such tuples and I need to extract all the tuples that come before a certain one lexicographically. Sorting works but takes too long.)

0 Answers
Related