NumPyunique函数

/ / NumPyunique函数

此函数在输入数组中返回唯一元素的数组,该函数可以返回唯一值数组和相关索引数组的元组。

numpy.unique(arr, return_index, return_inverse, return_counts)

参数说明,

Sr.No. Parameter & 描述
1

arr

输入数组。如果不是一维数组,将被展平

2

return_index

如果为True,则返回输入数组中元素的索引

3

return_inverse

如果为True,则返回唯一数组的索引,该索引可用于重建输入数组

4

return_counts

如果为True,则返回唯一数组中的元素出现在原始数组中的次数

import numpy as np 
a=np.array([5,2,6,2,7,5,6,8,2,9]) 

print 'First array:' 
print a 
print '\n'  

print 'Unique values of first array:' 
u=np.unique(a) 
print u 
print '\n'  

print 'Unique array and Indices array:' 
u,indices=np.unique(a, return_index=True) 
print indices 
print '\n'  

print 'We can see each number corresponds to index in original array:' 
print a 
print '\n'  

print 'Indices of unique array:' 
u,indices=np.unique(a,return_inverse=True) 
print u 
print '\n' 

print 'Indices are:' 
print indices 
print '\n'  

print 'Reconstruct the original array using indices:' 
print u[indices] 
print '\n'  

print 'Return the count of repetitions of unique elements:' 
u,indices=np.unique(a,return_counts=True) 
print u 
print indices

其输出如下-

First array:
[5 2 6 2 7 5 6 8 2 9]

Unique values of first array:
[2 5 6 7 8 9]

Unique array and Indices array:
[1 0 2 4 7 9]

We can see each number corresponds to index in original array:
[5 2 6 2 7 5 6 8 2 9]

Indices of unique array:
[2 5 6 7 8 9]

Indices are:
[1 0 2 0 3 1 2 4 0 5]

Reconstruct the original array using indices:
[5 2 6 2 7 5 6 8 2 9]

Return the count of repetitions of unique elements:
[2 5 6 7 8 9]
 [3 2 2 1 1 1]

祝学习愉快! (发现内容有误?请选中要编辑的内容 -> 右键 -> 修改 -> 提交!帮助我们改进教程质量)

精选教程推荐

👇 以下精选教程可能对您有帮助,拓展您的技术视野

大模型安全实战课 -〔赵帅〕

玩转AI创意写作 -〔于菁健〕

Rust程序设计(第2版) -〔Jim Blandy, Jason Orendorff, Leonora F. S. Tindall〕

手把手带你写一个 MiniTomcat -〔郭屹〕

Redis源码剖析与实战 -〔蒋德钧〕

陶辉的网络协议集训班02期 -〔陶辉〕

张汉东的Rust实战课 -〔张汉东〕

说透敏捷 -〔宋宁〕

移动端自动化测试实战 -〔思寒〕

📝 好记忆不如烂笔头,留下您的学习笔记吧!

暂无学习笔记,成为第一个分享的人吧!

您的笔记将帮助成千上万的学习者