Numpy.unique()函数的使用方法
Numpy.unique()函数是Numpy模块中的一个函数,它可以帮助用户获取数组中的唯一值。
import numpy as np a = np.array([1,2,3,3,4,4,5,6]) # 获取数组a中的唯一值 unique_a = np.unique(a) # 输出结果 print(unique_a)
上面的代码中,我们定义了一个numpy数组a,使用Numpy.unique()函数获取数组a中的唯一值,输出结果为:
[1 2 3 4 5 6]
可以看到,Numpy.unique()函数获取的唯一值是排序后的结果。
Numpy.unique()函数还可以接受两个参数,return_index和return_inverse,这两个参数可以控制函数的返回结果。
- return_index:如果设置为True,函数会返回唯一值在原始数组中的索引;
- return_inverse:如果设置为True,函数会返回原始数组中的值在唯一值数组中的索引。
import numpy as np a = np.array([1,2,3,3,4,4,5,6]) # 获取数组a中的唯一值,并返回唯一值在原始数组中的索引 unique_a, index = np.unique(a, return_index=True) # 获取数组a中的唯一值,并返回原始数组中的值在唯一值数组中的索引 unique_a, inverse = np.unique(a, return_inverse=True) # 输出结果 print(unique_a) print(index) print(inverse)
输出结果如下:
[1 2 3 4 5 6] [0 1 2 4 6 7] [0 1 2 2 3 3 4 5 6 6]
可以看到,return_index参数返回的是唯一值在原始数组中的索引,而return_inverse参数返回的是原始数组中的值在唯一值数组中的索引。
一下,Numpy.unique()函数的使用方法是:
- 定义一个numpy数组;
- 使用Numpy.unique()函数获取数组中的唯一值;
- 可以通过设置参数return_index和return_inverse来控制函数的返回结果。