Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.unique generates a list unique in what regard?

Tags:

python

numpy

If you input an array with general objects to numpy.unique, the result will be unique based upon what?

I have tried:

import numpy as np

class A(object): #probably exists a nice mixin for this :P
    def __init__(self, a):
        self.a = a
    def __lt__(self, other):
        return self.a < other.a
    def __le__(self, other):
        return self.a <= other.a
    def __eq__(self, other):
        return self.a == other.a
    def __ge__(self, other):
        return self.a >= other.a
    def __gt__(self, other):
        return self.a > other.a
    def __ne__(self, other):
        return self.a != other.a
    def __repr__(self):
        return "A({})".format(self.a)
    def __str__(self):
       return self.__repr__()

np.unique(map(A, range(3)+range(3)))

which returns

array([A(0), A(0), A(1), A(1), A(2), A(2)], dtype=object)

but my intentions are to get:

array([A(0), A(1), A(2)], dtype=object)
like image 961
SlimJim Avatar asked Dec 29 '25 09:12

SlimJim


1 Answers

Assuming the duplicate A(2) is a typo, I think you simply need to define __hash__ (see the docs):

import numpy as np
from functools import total_ordering

@total_ordering
class A(object):
    def __init__(self, a):
        self.a = a
    def __lt__(self, other):
        return self.a < other.a
    def __eq__(self, other):
        return self.a == other.a
    def __ne__(self, other):
        return self.a != other.a
    def __hash__(self):
        return hash(self.a)
    def __repr__(self):
        return "A({})".format(self.a)
    def __str__(self):
       return repr(self)

produces

>>> map(A, range(3)+range(3))
[A(0), A(1), A(2), A(0), A(1), A(2)]
>>> set(map(A, range(3)+range(3)))
set([A(0), A(1), A(2)])
>>> np.unique(map(A, range(3)+range(3)))
array([A(0), A(1), A(2)], dtype=object)

where I've used total_ordering to reduce the proliferation of methods, as you guessed was possible. :^)

[Edited after posting to correct missing __ne__.]

like image 139
DSM Avatar answered Dec 30 '25 22:12

DSM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!