此问题与“numpy.unique generates a list unique in what regard?”相关(但不相同)
设置:
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.unique([1, 1, 2, 2])
array([1, 2])
>>> np.unique(np.array([1, 1, 2, 2]))
array([1, 2])
>>> np.unique(map(UniqueObject, [1, 1, 2, 2]))
array([UniqueObject(1), UniqueObject(2)], dtype=object)
这没问题,它可以工作。但这并不像预期的那样工作:
>>> 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)) #?
我正在运行 numpy 1.8.0.dev-74b08b3
和 Python 2.7.3
最佳答案
按照np.unique
的源码,好像真正走的分支是
else:
ar.sort()
flag = np.concatenate(([True], ar[1:] != ar[:-1]))
return ar[flag]
它只是对术语进行排序,然后取与前一个不相等的那些。但这不应该起作用吗?..哎呀。这是在我身上。您的原始代码定义了 __ne__
,我在删除被 total_ordering
编辑的比较时不小心删除了它。
>>> UniqueObject(1) == UniqueObject(1)
True
>>> UniqueObject(1) != UniqueObject(1)
True
将 __ne__
放回:
>>> 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)
关于python - numpy.unique 对 numpy.array 的对象表现得很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16400979/