Python numpy.unique对numpy.array对象的行为异常
此问题与“”有关(但与“”不同) 设置:Python numpy.unique对numpy.array对象的行为异常,python,numpy,Python,Numpy,此问题与“”有关(但与“”不同) 设置: import numpy as np from functools import total_ordering @total_ordering class UniqueObject(object): def __init__(self, a): self.a = a def __eq__(self, other): return self.a == other.a def __lt__(self,
import numpy as np
from functools import total_ordering
@total_ordering
class UniqueObject(object):
def __init__(self, a):
self.a = a
def __eq__(self, other):
return self.a == other.a
def __lt__(self, other):
return self.a < other.a
def __hash__(self):
return hash(self.a)
def __str__(self):
return "UniqueObject({})".format(self.a)
def __repr__(self):
return self.__str__()
这没问题,它很管用。但这并不像预期的那样有效:
>>> np.unique(np.array(map(UniqueObject, [1, 1, 2, 2])))
array([UniqueObject(1), UniqueObject(1), UniqueObject(2), UniqueObject(2)], dtype=object)
为什么处理dtype=object的np.array与处理对象的python列表不同
即:
objs = map(UniqueObject, [1, 1, 2, 2])
np.unique(objs) != np.unique(np.array(objs)) #?
我正在运行
numpy1.8.0.dev-74b08b3
和python2.7.3
通过np.unique
的源代码,看起来实际执行的分支是
else:
ar.sort()
flag = np.concatenate(([True], ar[1:] != ar[:-1]))
return ar[flag]
它只是对术语进行排序,然后取与前一个不相等的术语。但这不应该奏效吗?。。哎呀。我请客。您的原始代码定义了\uuu ne\uuuu
,我在删除正在排序的比较时意外地删除了它
>>> UniqueObject(1) == UniqueObject(1)
True
>>> UniqueObject(1) != UniqueObject(1)
True
将\uuu ne\uuu
放回:
>>> UniqueObject(1) != UniqueObject(1)
False
>>> np.array(map(UniqueObject, [1,1,2,2]))
array([UniqueObject(1), UniqueObject(1), UniqueObject(2), UniqueObject(2)], dtype=object)
>>> np.unique(np.array(map(UniqueObject, [1,1,2,2])))
array([UniqueObject(1), UniqueObject(2)], dtype=object)
>>> UniqueObject(1) != UniqueObject(1)
False
>>> np.array(map(UniqueObject, [1,1,2,2]))
array([UniqueObject(1), UniqueObject(1), UniqueObject(2), UniqueObject(2)], dtype=object)
>>> np.unique(np.array(map(UniqueObject, [1,1,2,2])))
array([UniqueObject(1), UniqueObject(2)], dtype=object)