Numpy.unique Generates A List Unique In What Regard?
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 mi
Solution 1:
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_orderingclassA(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):
returnhash(self.a)
def__repr__(self):
return"A({})".format(self.a)
def__str__(self):
returnrepr(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__
.]
Post a Comment for "Numpy.unique Generates A List Unique In What Regard?"