python – numpy.unique对numpy.array对象的行为很奇怪
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – numpy.unique对numpy.array对象的行为很奇怪,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1739字,纯文字阅读大概需要3分钟。
内容图文
![python – numpy.unique对numpy.array对象的行为很奇怪](/upload/InfoBanner/zyjiaocheng/785/236494e22d9f4efdb13726b6b5fef542.jpg)
这个问题与“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)
为什么np.array与dtype = object的处理方式不同于带有对象的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-ed的比较时意外删除了它.
>>> 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对象的行为很奇怪全部内容,希望文章能够帮你解决python – numpy.unique对numpy.array对象的行为很奇怪所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。