Numpy-unique

提供:Dev Guides
移動先:案内検索

numpy.unique

この関数は、入力配列内の一意の要素の配列を返します。 この関数は、一意の値の配列のタプルと関連するインデックスの配列を返すことができます。 インデックスの性質は、関数呼び出しの戻りパラメーターのタイプに依存します。

numpy.unique(arr, return_index, return_inverse, return_counts)

どこで、

Sr.No. Parameter & Description
1

arr

入力配列。 1次元配列でない場合は平坦化されます

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]