日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

numpy.unique()使用方法_python

作者:瞻邈 ? 更新時(shí)間: 2023-05-21 編程語言

numpy.unique() 函數(shù)接受一個(gè)數(shù)組,去除其中重復(fù)元素,并按元素由小到大返回一個(gè)新的無元素重復(fù)的元組或者列表。

1. 參數(shù)說明

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ú)一無二的數(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出來,
#                                    # 下面 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()函數(shù)

numpy.unique — NumPy v1.24 Manual

原文鏈接:https://blog.csdn.net/xhtchina/article/details/129025249

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新