如何在numpy数组中查找唯一的对象?

3

看起来np.unique并不是在所有情况下都支持objects

v = np.array(["abc",None,1,2,3,"3",2])
np.unique(v, return_counts=True)

导致 TypeError: ‘<’ 不支持 NoneType 实例和 str 实例之间的比较错误。

TypeError: '<' not supported between instances of 'NoneType' and 'str'

我可以使用 np.unique(v.astype(str)),但这将失去 3"3" 之间的区别。这是唯一的方法吗?


None 不支持比较运算符 < >。 - Epsi95
@Epsi95:None == "3" 运行良好。而 "3" < 3 也不起作用。那么呢? - sds
这是正确的,因为None在前面,所以它被捕获了。尝试使用v = np.array(["abc",1,2,3,"3",2,None,]) - Epsi95
2个回答

0

numpy.uniquehelp文档中写道:

unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)
    Find the unique elements of an array.
    
    Returns the sorted unique elements of an array. There are three optional
    outputs in addition to the unique elements:
    
    * the indices of the input array that give the unique values
    * the indices of the unique array that reconstruct the input array
    * the number of times each unique value comes up in the input array
    
    Parameters
    ----------
    ar : array_like
        Input array. Unless `axis` is specified, this will be flattened if it
        is not already 1-D.

因此,它失败了,因为您的一个对象没有排序所需的__lt__方法。如果您只想找到唯一的内容,但顺序对您不重要,可以执行以下操作。
import collections
import numpy as np
v = np.array(["abc",None,1,2,3,"3",2])
cnt = collections.Counter(v.ravel())
uniq = [k for k,v in cnt.items() if v==1]
print(uniq)

输出:

['abc', None, 1, 3, '3']

或者只需使用set(v),无需集合。 - tdelaney

0

一种方法是为数组中的所有对象定义__lt__。另一种更简单的方法是使用Python中的set,它不需要排序,只依赖于等号运算符(仅适用于可洗涤对象):

np.array(list(set(v)))

输出:

array([1, 2, 3, None, '3', 'abc'], dtype=object)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接