np.unique
是 NumPy 庫中的一個函數,用於找出陣列
中的相同的數值。這個函數可以單純過濾只取唯一值出來,也可以選擇性地返回這些唯一值在原始陣列
中的中的索引和計數。
函式
unique = np.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)
參數
ar
: 輸入數組。可以是任何形狀的陣列
。return_index
: 如果設置為 True,將返回唯一值在原始陣列
中的索引。return_inverse
: 如果設置為 True,將返回原始數組重構為唯一值陣列
的索引。return_counts
: 如果設置為 True,將返回唯一值的計數。axis
: 如果設置,則沿指定軸查找唯一值。
返回值
unique
: 唯一值的陣列
,按照排序順序返回。unique_indices
: (可選)唯一值在原始數組中的第一個出現索引。unique_inverse
: (可選)用於重構原始數組的索引。unique_counts
: (可選)唯一值的計數。
使用範例
單純使用 找出唯一值
import numpy as np
# 1D
a = np.unique([1, 1, 2, 2, 3, 3])
print(a) # [1 2 3]
# 2D
b = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
b_res = np.unique(b, axis=0)
print(b_res)
#[[1 0 0]
# [2 3 4]]
取出唯一值的索引
返回出兩個陣列,第一個u包含的是唯一值,第二個indices包含的是這些唯一值的索引。import numpy as np
a = np.array(['a', 'b', 'b', 'c', 'a'])
u, indices = np.unique(a, return_index=True)
print(u) #['a' 'b' 'c']
print(indices) #[0 1 3]
print(a[indices]) #['a' 'b' 'c']
重構索引數組
import numpy as np
a = np.array([1, 2, 6, 4, 2, 3, 2])
u, indices = np.unique(a, return_inverse=True)
print(u) # [1 2 3 4 6]
print(indices) #[0 1 4 3 1 2 1]
print(u[indices]) #[1 2 6 4 2 3 2]
分步解釋
- 原始數組 a:
a = np.array([1, 2, 6, 4, 2, 3, 2])
- 原始數組 a 包含了以下元素: [1, 2, 6, 4, 2, 3, 2]
- 調用 np.unique 並返回唯一值和重構索引:
u, indices = np.unique(a, return_inverse=True)
- u 是 a 中的唯一值,並且是排序後的結果。
- indices 是一個數組,它包含了 a 中每個元素在 u 中的位置索引。
- 唯一值數組 u:
print(u) # [1 2 3 4 6]
- u 包含了 a 中的唯一值,並且是排序後的結果: [1, 2, 3, 4, 6]
- 重構索引數組 indices:
print(indices) # [0 1 4 3 1 2 1]
- indices 包含了 a 中每個元素在 u 中的位置索引。1 在 u 中的位置是 02 在 u 中的位置是 16 在 u 中的位置是 44 在 u 中的位置是 32 在 u 中的位置是 13 在 u 中的位置是 22 在 u 中的位置是 1
- 重構原始數組 a:
print(u[indices]) # [1 2 6 4 2 3 2]
- 使用 u 和 indices 可以重構原始數組 a。
- u[indices] 會將 indices 中的每個索引替換為 u 中相應的位置的值,從而得到原始數組 a。
計算唯一值出現的次數
返回出兩個陣列,第一個values包含的是唯一值,第二個counts包含的是這些唯一值出現的次數。
import numpy as np
a = np.array([1, 2, 6, 4, 2, 3, 2])
values, counts = np.unique(a, return_counts=True)
print(values) #[1 2 3 4 6]
print(counts) #[1 3 1 1 1]