numpy去除重复出现的元素 numpy.unique

您所在的位置:网站首页 python对字典中的值排序并去掉重复元素 numpy去除重复出现的元素 numpy.unique

numpy去除重复出现的元素 numpy.unique

2024-07-16 17:27| 来源: 网络整理| 查看: 265

函数

numpy.unique(ar,return_index=False,return_counts=False, axis=None)

Find the unique elements of an array.

官方链接

ar: Input array. Unless axis is specified, this will be flattened if it is not already 1-D. return_index (optional): If True, also return the indices of ar (along the specified axis, if provided, or in the flattened array) that result in the unique array. return_countsbool (optional): If True, also return the number of times each unique item appears in ar. axis(optional): The axis to operate on. If None, ar will be flattened. If an integer, the subarrays indexed by the given axis will be flattened and treated as the elements of a 1-D array with the dimension of the given axis,

把ar沿着axis进行切片,并把切片结果中重复的元素去掉

示例1 如果想把一维向量中重复的元素去掉:

import numpy as np mat= np.array([1, 1, 2, 2, 3, 3]) print(np.unique(mat))

结果

[1 2 3]

对于多维矩阵依然适用:

import numpy as np mat= np.array([[1, 1], [2, 3]]) print(np.unique(mat))

结果

[1 2 3]

示例2. 指定 axis 如果要把矩阵 mat=np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]]) 中冗余的行去掉,则可以指定 axis=0 , 这样,矩阵就会被切片成 mat[0,:] , mat[1,:] , mat[2,:],对应矩阵的三行,并把冗余的行去掉。 若指定 axis=1 ,这样,矩阵就会被切片成 mat[:,0] , mat[:,1] , mat[:,2],对应矩阵的三列,并把冗余的列去掉。 示例:

import numpy as np mat= np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]]) print(np.unique(mat,axis=0))

结果:

[[1 0 0] [2 3 4]]

示例3. return_index 返回去掉冗余后的结果中,每个element 第一次出现时对应的下标: 示例:

import numpy as np mat= np.array([1, 1, 2, 2, 3, 3]) u,indices=np.unique(mat,return_index=True) print('u=',u,'indices=',indices)

结果:

u= [1 2 3] indices= [0 2 4]

示例:

import numpy as np mat= np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]]) u,indices=np.unique(mat,return_index=True,axis=0) print('u=',u,'indices=',indices)

结果:

u= [[1 0 0] [2 3 4]] indices= [0 2]

示例4. return_counts 返回每种元素的计数:

import numpy as np mat= np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]]) u,indices,counts=np.unique(mat,return_index=True,return_counts=True,axis=0) print('u=',u,'indices=',indices,'counts=',counts)

结果:

u= [[1 0 0] [2 3 4]] indices= [0 2] counts= [2 1]


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3