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



在所有情况下np.unique并不完全支持objects:

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

在搜索结果

TypeError: '<'在'NoneType'和'str'实例之间不支持

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

helpofnumpy.uniquesaid

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']

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

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

输出:

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

最新更新