【问题标题】:How to find unique objects in a numpy array?如何在 numpy 数组中找到唯一的对象?
【发布时间】:2021-02-01 18:28:26
【问题描述】:

似乎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" 之间的区别。 这是唯一的方法吗?

【问题讨论】:

  • None 不支持比较
  • @Epsi95: None == "3" 工作得很好。 "3" < 3 也不起作用。所以?!
  • 确实如此,因为在此之前 None 就是它被捕获的原因。试试v = np.array(["abc",1,2,3,"3",2,None,])

标签: python numpy unique


【解决方案1】:

help of numpy.unique

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)。无需收藏。
【解决方案2】:

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

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

输出:

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

【讨论】:

    猜你喜欢
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-13
    • 2020-12-19
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    相关资源
    最近更新 更多