np.unique()的具體使用
一、np.unique() 介紹
對于一維數(shù)組或者列表,np.unique() 函數(shù) 去除其中重復的元素 ,并按元素 由小到大 返回一個新的無元素重復的元組或者列表。
二、np.unique() 原型
numpy.unique(arr, return_index, return_inverse, return_counts)
- arr:輸入數(shù)組,如果不是一維數(shù)組則會展開
- return_index:如果為 true,返回新列表元素在舊列表中的位置(下標),并以列表形式存儲。
- return_inverse:如果為true,返回舊列表元素在新列表中的位置(下標),并以列表形式存儲。
- return_counts:如果為 true,返回去重數(shù)組中的元素在原數(shù)組中的出現(xiàn)次數(shù)。
三、實例
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]) ? ? # 使用下標重構原數(shù)組
print("______")
a, indices = np.unique(A, return_counts=True) ? ?# 每個元素在舊列表里各自出現(xiàn)了幾次
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函數(shù)解析
np.unique()
到此這篇關于np.unique()的具體使用的文章就介紹到這了,更多相關np.unique()使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

