NumPy 数组操作 numpy.unique
该函数返回输入数组中唯一元素的数组。该函数能够返回一个包含唯一值数组和关联索引数组的元组。索引的性质取决于函数调用中返回参数的类型。
numpy.unique(arr, return_index, return_inverse, return_counts)
其中,
序号 | 参数和描述 |
---|---|
1 | arr 输入数组。如果不是一维数组,将被展平 |
2 | return_index 如果为True,则返回输入数组中元素的索引 |
3 | return_inverse 如果为True,则返回数组中唯一元素的索引,可以用来重构输入数组 |
4 | return_counts 如果为True,则返回原始数组中唯一数组元素出现的次数 |
示例
import numpy as np
a = np.array([5,2,6,2,7,5,6,8,2,9])
print 'First array:'
print a
print '\n'
print 'Unique values of first array:'
u = np.unique(a)
print u
print '\n'
print 'Unique array and Indices array:'
u,indices = np.unique(a, return_index = True)
print indices
print '\n'
print 'We can see each number corresponds to index in original array:'
print a
print '\n'
print 'Indices of unique array:'
u,indices = np.unique(a,return_inverse = True)
print u
print '\n'
print 'Indices are:'
print indices
print '\n'
print 'Reconstruct the original array using indices:'
print u[indices]
print '\n'
print 'Return the count of repetitions of unique elements:'
u,indices = np.unique(a,return_counts = True)
print u
print indices
它的输出如下所示−
First array:
[5 2 6 2 7 5 6 8 2 9]
Unique values of first array:
[2 5 6 7 8 9]
Unique array and Indices array:
[1 0 2 4 7 9]
We can see each number corresponds to index in original array:
[5 2 6 2 7 5 6 8 2 9]
Indices of unique array:
[2 5 6 7 8 9]
Indices are:
[1 0 2 0 3 1 2 4 0 5]
Reconstruct the original array using indices:
[5 2 6 2 7 5 6 8 2 9]
Return the count of repetitions of unique elements:
[2 5 6 7 8 9]
[3 2 2 1 1 1]