本文簡要介紹 python 語言中 numpy.unique
的用法。
用法:
numpy.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None)
查找數組的唯一元素。
返回數組的排序唯一元素。除了獨特的元素外,還有三個可選輸出:
給出唯一值的輸入數組的索引
重建輸入數組的唯一數組的索引
每個唯一值在輸入數組中出現的次數
- ar: array_like
輸入數組。除非指定了軸,否則如果它不是一維的,它將被展平。
- return_index: 布爾型,可選
如果為 True,還返回導致唯一數組的 ar 的索引(沿著指定的軸,如果提供,或者在展平數組中)。
- return_inverse: 布爾型,可選
如果為 True,則還返回可用於重建 ar 的唯一數組的索引(對於指定的軸,如果提供)。
- return_counts: 布爾型,可選
如果為 True,還返回每個唯一項目在 ar 中出現的次數。
- axis: int 或無,可選
要操作的軸。如果沒有,ar 將被展平。如果是整數,則由給定軸索引的子數組將被展平並被視為具有給定軸維度的一維數組的元素,有關更多詳細信息,請參閱注釋。如果使用axis kwarg,則不支持包含對象的對象數組或結構化數組。默認值為無。
- unique: ndarray
排序後的唯一值。
- unique_indices: ndarray,可選
原始數組中第一次出現的唯一值的索引。僅在 return_index 為 True 時提供。
- unique_inverse: ndarray,可選
從唯一數組重建原始數組的索引。僅在 return_inverse 為 True 時提供。
- unique_counts: ndarray,可選
每個唯一值在原始數組中出現的次數。僅在 return_counts 為 True 時提供。
參數:
返回:
注意:
當指定軸時,由軸索引的子數組被排序。這是通過使指定的軸成為數組的第一個維度(將軸移動到第一個維度以保持其他軸的順序)然後按 C 順序展平子數組來完成的。然後將展平的子數組視為結構化類型,每個元素都給定一個標簽,其效果是我們最終得到一個結構化類型的一維數組,可以以與任何其他一維數組相同的方式處理。結果是展平的子數組從第一個元素開始按字典順序排序。
例子:
>>> np.unique([1, 1, 2, 2, 3, 3]) array([1, 2, 3]) >>> a = np.array([[1, 1], [2, 3]]) >>> np.unique(a) array([1, 2, 3])
返回二維數組的唯一行
>>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]]) >>> np.unique(a, axis=0) array([[1, 0, 0], [2, 3, 4]])
返回給出唯一值的原始數組的索引:
>>> a = np.array(['a', 'b', 'b', 'c', 'a']) >>> u, indices = np.unique(a, return_index=True) >>> u array(['a', 'b', 'c'], dtype='<U1') >>> indices array([0, 1, 3]) >>> a[indices] array(['a', 'b', 'c'], dtype='<U1')
從唯一值和逆重構輸入數組:
>>> a = np.array([1, 2, 6, 4, 2, 3, 2]) >>> u, indices = np.unique(a, return_inverse=True) >>> u array([1, 2, 3, 4, 6]) >>> indices array([0, 1, 4, 3, 1, 2, 1]) >>> u[indices] array([1, 2, 6, 4, 2, 3, 2])
從唯一值和計數重構輸入值:
>>> a = np.array([1, 2, 6, 4, 2, 3, 2]) >>> values, counts = np.unique(a, return_counts=True) >>> values array([1, 2, 3, 4, 6]) >>> counts array([1, 3, 1, 1, 1]) >>> np.repeat(values, counts) array([1, 2, 2, 2, 3, 4, 6]) # original order not preserved
相關用法
- Python numpy union1d用法及代碼示例
- Python numpy unpackbits用法及代碼示例
- Python numpy unravel_index用法及代碼示例
- Python numpy unwrap用法及代碼示例
- Python numpy ufunc.at用法及代碼示例
- Python numpy ufunc.outer用法及代碼示例
- Python numpy ufunc.ntypes用法及代碼示例
- Python numpy ufunc.identity用法及代碼示例
- Python numpy ufunc.reduce用法及代碼示例
- Python numpy ufunc.nin用法及代碼示例
- Python numpy ufunc.nout用法及代碼示例
- Python numpy ufunc.reduceat用法及代碼示例
- Python numpy ufunc.nargs用法及代碼示例
- Python numpy ufunc.types用法及代碼示例
- Python numpy ufunc.signature用法及代碼示例
- Python numpy ufunc.accumulate用法及代碼示例
- Python numpy RandomState.standard_exponential用法及代碼示例
- Python numpy hamming用法及代碼示例
- Python numpy legendre.legint用法及代碼示例
- Python numpy chararray.ndim用法及代碼示例
- Python numpy chebyshev.chebsub用法及代碼示例
- Python numpy chararray.nbytes用法及代碼示例
- Python numpy ma.indices用法及代碼示例
- Python numpy matrix.A1用法及代碼示例
- Python numpy MaskedArray.var用法及代碼示例
注:本文由純淨天空篩選整理自numpy.org大神的英文原創作品 numpy.unique。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。