【Python】np.unique() 介绍与使用

文章目录

  • 一、np.unique() 介绍
  • 二、np.unique() 原型
  • 三、实例
  • 参考链接

  • 一、np.unique() 介绍

    对于一维数组或者列表,np.unique() 函数 去除其中重复的元素 ,并按元素 由小到大 返回一个新的无元素重复的元组或者列表。


    二、np.unique() 原型

    numpy.unique(arr, return_index, return_inverse, return_counts)
    
  • arr:输入数组,如果不是一维数组则会展开
  • return_index:如果为 true,返回新列表元素在旧列表中的位置(下标),并以列表形式存储。
  • return_inverse:如果为true,返回旧列表元素在新列表中的位置(下标),并以列表形式存储。
  • return_counts:如果为 true,返回去重数组中的元素在原数组中的出现次数。

  • 三、实例

    import numpy as np
    A = [1, 2, 2, 5, 3, 4, 3]
    a = np.unique(A)
    print(a)
    print("______")
    
    a, indices = np.unique(A, return_index=True)   # 返回新列表元素在旧列表中的位置(下标)
    print(a)		 # 列表
    print(indices)	 # 下标
    print("______")
    
    a, indices = np.unique(A, return_inverse=True)   # 旧列表的元素在新列表的位置
    print(a)
    print(indices)
    print(a[indices])     # 使用下标重构原数组
    print("______")
    
    a, indices = np.unique(A, return_counts=True)    # 每个元素在旧列表里各自出现了几次
    print(a)
    print(indices)
    print("______")
    
    B = ([1, 2], [2, 5], [3, 4])
    b = np.unique(B)
    C= ['fgfh','asd','fgfh','asdfds','wrh']
    c= np.unique(C)
    print(b)
    print(c)
    

    输出结果:

    [1 2 3 4 5]
    ______
    [1 2 3 4 5]
    [0 1 4 5 3]
    ______
    [1 2 3 4 5]
    [0 1 1 4 2 3 2]
    [1 2 2 5 3 4 3]
    ______
    [1 2 3 4 5]
    [1 2 2 1 1]
    ______
    [1 2 3 4 5]
    ['asd' 'asdfds' 'fgfh' 'wrh']
    

    参考链接

    1. Python中numpy库unique函数解析
    2. np.unique()

    来源:想变厉害的大白菜

    物联沃分享整理
    物联沃-IOTWORD物联网 » 【Python】np.unique() 介绍与使用

    发表评论