np.unique()的具體使用
更新時間:2023年03月14日 10:38:33 作者:想變厲害的大白菜
本文主要介紹了np.unique()的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
一、np.unique() 介紹
對于一維數組或者列表,np.unique() 函數 去除其中重復的元素 ,并按元素 由小到大 返回一個新的無元素重復的元組或者列表。
二、np.unique() 原型
numpy.unique(arr, return_index, return_inverse, return_counts)
- arr:輸入數組,如果不是一維數組則會展開
- return_index:如果為 true,返回新列表元素在舊列表中的位置(下標),并以列表形式存儲。
- return_inverse:如果為true,返回舊列表元素在新列表中的位置(下標),并以列表形式存儲。
- return_counts:如果為 true,返回去重數組中的元素在原數組中的出現次數。
三、實例
import numpy as np A = [1, 2, 2, 5, 3, 4, 3] a = np.unique(A) print(a) print("______") a, indices = np.unique(A, return_index=True) ? # 返回新列表元素在舊列表中的位置(下標) print(a)?? ??? ? # 列表 print(indices)?? ? # 下標 print("______") a, indices = np.unique(A, return_inverse=True) ? # 舊列表的元素在新列表的位置 print(a) print(indices) print(a[indices]) ? ? # 使用下標重構原數組 print("______") a, indices = np.unique(A, return_counts=True) ? ?# 每個元素在舊列表里各自出現了幾次 print(a) print(indices) print("______") B = ([1, 2], [2, 5], [3, 4]) b = np.unique(B) C= ['fgfh','asd','fgfh','asdfds','wrh'] c= np.unique(C) print(b) print(c)
輸出結果:
[1 2 3 4 5]
______
[1 2 3 4 5]
[0 1 4 5 3]
______
[1 2 3 4 5]
[0 1 1 4 2 3 2]
[1 2 2 5 3 4 3]
______
[1 2 3 4 5]
[1 2 2 1 1]
______
[1 2 3 4 5]
['asd' 'asdfds' 'fgfh' 'wrh']
參考鏈接
Python中numpy庫unique函數解析
np.unique()
到此這篇關于np.unique()的具體使用的文章就介紹到這了,更多相關np.unique()使用內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!