numpy.unique()使用方法
numpy.unique() 函數(shù)接受一個(gè)數(shù)組,去除其中重復(fù)元素,并按元素由小到大返回一個(gè)新的無(wú)元素重復(fù)的元組或者列表。
1. 參數(shù)說(shuō)明
numpy.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None, *, equal_nan=True)
ar:輸入數(shù)組,除非設(shè)定了下面介紹的axis參數(shù),否則輸入數(shù)組均會(huì)被自動(dòng)扁平化成一個(gè)一維數(shù)組。
return_index:(可選參數(shù),布爾類型),如果為True則結(jié)果會(huì)同時(shí)返回被提取元素在原始數(shù)組中的索引值(index)。
return_inverse:(可選參數(shù),布爾類型),如果為True則結(jié)果會(huì)同時(shí)返回元素位于原始數(shù)組的索引值(index)。
return_counts:(可選參數(shù),布爾類型),如果為True則結(jié)果會(huì)同時(shí)每個(gè)元素在原始數(shù)組中出現(xiàn)的次數(shù)。
axis:計(jì)算唯一性時(shí)的軸
返回值:返回一個(gè)排好序列的獨(dú)一無(wú)二的數(shù)組。
2. 示例
2.1. 一維數(shù)組
np.unique([1, 1, 2, 2, 3, 3]) a = np.array([[1, 1], [2, 3]])
結(jié)果
array([1, 2, 3])
2.2. 二維數(shù)組
a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]]) np.unique(a, axis=0)
結(jié)果
array([[1, 0, 0], [2, 3, 4]])
2.3. 返回索引
a = np.array(['a', 'b', 'b', 'c', 'a']) u, indices = np.unique(a, return_index=True)
結(jié)果
array([0, 1, 3])
array(['a', 'b', 'c'], dtype='<U1')
2.4. 重建輸入矩陣
a = np.array([1, 2, 6, 4, 2, 3, 2]) u, indices = np.unique(a, return_inverse=True) u[indices]
結(jié)果
array([1, 2, 3, 4, 6])
array([0, 1, 4, 3, 1, 2, 1])
array([1, 2, 6, 4, 2, 3, 2])
示例:嘗試用參數(shù) return_counts 解決一個(gè)小問題。
# coding: utf-8 import numpy as np # 任務(wù): 統(tǒng)計(jì) a 中元素個(gè)數(shù), 找出出現(xiàn)次數(shù)最多的元素 a = np.array([1, 1, 1, 3, 3, 2, 2, 2, 2, 4, 5, 5]) # numpy.unique() 測(cè)試 b = np.unique(a) print(b) # 使用 return_counts=True 統(tǒng)計(jì)元素重復(fù)次數(shù) b, count = np.unique(a, return_counts=True) print(b, count) # 使用 zip 將元素和其對(duì)應(yīng)次數(shù)打包成一個(gè)個(gè)元組, 返回元組的列表 zipped = zip(b, count) # for i, counts in zipped: # print("%d: %d" % (i, counts)) # 這里打印zipped出來(lái), # # 下面 max()會(huì)報(bào) # # ValueError: max() arg is an empty sequence # # 不知道為什么 >_< # 使用 max() 函數(shù)找出出現(xiàn)次數(shù)最多的元素 target = max(zipped, key=lambda x: x[1]) print(target)
參考文獻(xiàn)
numpy.unique — NumPy v1.24 Manual
到此這篇關(guān)于numpy.unique()使用方法的文章就介紹到這了,更多相關(guān)numpy.unique()內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- python 的numpy庫(kù)中的mean()函數(shù)用法介紹
- Python的numpy庫(kù)中將矩陣轉(zhuǎn)換為列表等函數(shù)的方法
- python numpy之np.random的隨機(jī)數(shù)函數(shù)使用介紹
- numpy下的flatten()函數(shù)用法詳解
- Python numpy 常用函數(shù)總結(jié)
- Python numpy.power()函數(shù)使用說(shuō)明
- 淺析python中numpy包中的argsort函數(shù)的使用
- Numpy中stack(),hstack(),vstack()函數(shù)用法介紹及實(shí)例
- python使用numpy中的size()函數(shù)實(shí)例用法詳解
- python中numpy.empty()函數(shù)實(shí)例講解
相關(guān)文章
python基于TCP實(shí)現(xiàn)的文件下載器功能案例
這篇文章主要介紹了python基于TCP實(shí)現(xiàn)的文件下載器功能,結(jié)合具體實(shí)例形式分析了Python使用socket模塊實(shí)現(xiàn)的tcp協(xié)議下載功能客戶端與服務(wù)器端相關(guān)操作技巧,需要的朋友可以參考下2019-12-12python淺析守護(hù)線程與非守護(hù)線程的區(qū)別與使用
守護(hù)線程,又稱后臺(tái)線程,它是在后臺(tái)運(yùn)行的,如果所有前臺(tái)線程都死亡,那么后臺(tái)線程就會(huì)自動(dòng)死亡,本章我們來(lái)了解守護(hù)線程與非守護(hù)線程,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-08-08