代码之家  ›  专栏  ›  技术社区  ›  sds Niraj Rajbhandari

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

  •  0
  • sds Niraj Rajbhandari  · 技术社区  · 4 年前

    看来 np.unique 不太支持 objects 在所有情况下:

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

    结果在

    类型错误:“<”“NoneType”和“str”的实例之间不支持

    我能行 np.unique(v.astype(str)) 但这将失去两者之间的区别 3 "3" . 这是唯一的办法吗?

    1 回复  |  直到 4 年前
        1
  •  0
  •   Daweo    4 年前

    help 属于 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']
    
        2
  •  0
  •   Ehsan    4 年前

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

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

    输出:

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