np.unique()

np.unique(ar, return_index=False, return_inverse=False, return_counts=False,axis=None)
去除数组中的重复数字,并进行排序后输出

不选参数:

>>> b=np.random.randint(0,5, size=(10))
>>> b
array([1, 4, 3, 0, 1, 0, 0, 1, 4, 4])
>>> np.unique(b)
array([0, 1, 3, 4])

对于含有重复元素的数组,提取其中所有出现元素,并且返回排序后结果。

对于二维数组:

>>> c=np.random.randint(0,5,size=(3,4))
>>> c
array([[1, 0, 2, 4],
       [1, 3, 3, 1],
       [1, 4, 0, 1]])
>>> np.unique(c)
array([0, 1, 2, 3, 4])

return_index=True
返回新列表中每个元素在原列表中第一次出现的索引值

>>> b=np.random.randint(0,5, size=(10))
>>> b
array([1, 4, 3, 0, 1, 0, 0, 1, 4, 4])
>>> np.unique(b, return_index=True)
(array([0, 1, 3, 4]), array([3, 0, 2, 1], dtype=int64))

除了返回不含重复元素的一维数组,还有一个数组,对应前面那个一维数组中元素第一次出现的位置。

对于二维数组:

>>> c=np.random.randint(0,5,size=(3,4))
>>> c
array([[1, 0, 2, 4],
       [1, 3, 3, 1],
       [1, 4, 0, 1]])
>>> np.unique(c, return_index=True)
(array([0, 1, 2, 3, 4]), array([1, 0, 2, 5, 3], dtype=int64))

可以看见它是先把矩阵拉伸成一维数组,然后再排。(按行展)

return_inverse=True
返回原列表中的每个元素在新列表中出现的索引值,元素个数与原列表中元素个数一致

对一维数组:

>>> b=np.random.randint(0,5, size=(10))
>>> b
array([1, 4, 3, 0, 1, 0, 0, 1, 4, 4])
>>> np.unique(b, return_index=True, return_inverse=True)
(array([0, 1, 3, 4]), array([3, 0, 2, 1], dtype=int64), array([1, 3, 2, 0, 1, 0, 0, 1, 3, 3], dtype=int64))

又多返回了一个数组,可以看出这个数组是返回原各个元素在第一个矩阵array([0,1,3,4])中的位置。

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

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

print 'Return the count of repetitions of unique elements:'
u,indices = np.unique(a,return_counts = True)
print u
print indices
Return the count of repetitions of unique elements:
[2 5 6 7 8 9]
 [3 2 2 1 1 1]
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值