NumPy unique() 函式



NumPy 的unique()函式用於返回陣列中排序後的唯一元素。它還可以選擇性地返回輸入陣列中給出唯一值的索引以及每個唯一值的計數。

此函式可用於從陣列中刪除重複項並瞭解元素的頻率。

語法

以下是 NumPy unique()函式的語法:

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

引數

以下是 NumPy unique()函式的引數:

  • arr: 輸入陣列。如果不是一維陣列,將被展平。
  • return_index: 如果為 True,則返回輸入陣列中元素的索引。
  • return_inverse: 如果為 True,則返回唯一陣列的索引,可用於重建輸入陣列。
  • return_counts: 如果為 True,則返回唯一陣列中元素在原始陣列中出現的次數。

示例 1

以下是 NumPy unique()函式的示例,其中建立了一個包含給定輸入陣列唯一值的陣列:

import numpy as np 

# Create a 1D array
a = np.array([5, 2, 6, 2, 7, 5, 6, 8, 2, 9]) 

print('First array:') 
print(a) 
print('\n')  

# Get unique values in the array
print('Unique values of first array:') 
u = np.unique(a) 
print(u) 
print('\n')  

輸出

First array:
[5 2 6 2 7 5 6 8 2 9]


Unique values of first array:
[2 5 6 7 8 9]

示例 2

在本示例中,我們使用 unique() 函式獲取唯一值及其索引:

import numpy as np 

# Create a 1D array
a = np.array([5, 2, 6, 2, 1, 7, 5, 6, 8, 2, 9]) 

print('First array:') 
print(a) 
print('\n')   

# Get unique values and their indices in the original array
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')   

輸出

First array:
[5 2 6 2 1 7 5 6 8 2 9]


Unique array and Indices array:
[ 4  1  0  2  5  8 10]


We can see each number corresponds to index in original array:
[5 2 6 2 1 7 5 6 8 2 9]

示例 3

以下是使用唯一元素及其索引重建原始陣列的示例:

import numpy as np 

# Create a 1D array
a = np.array([5, 2, 6, 2, 7, 5, 6, 8, 2, 9]) 

print('First array:') 
print(a) 
print('\n')  

# Get unique values and indices to reconstruct the original array
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')  

# Get counts of unique values
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]


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]
numpy_array_manipulation.htm
廣告