【Numpy】np.unique去重复

本文深入探讨了NumPy库中unique函数的高级用法,包括去除数组中的重复元素,返回唯一元素的索引,以及如何按行去重。通过实例展示了如何使用return_index和return_inverse参数来获取原始数组中唯一元素的位置和重建原数组所需索引。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

numpy.unique(arreturn_index=Falsereturn_inverse=Falsereturn_counts=Falseaxis=None)

去除重复,返回索引值,排序

>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])

按行进行去重复 

>>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
>>> np.unique(a, axis=0)
array([[1, 0, 0], [2, 3, 4]])

return_index将得到结果对应于原始数组中的索引值。 

>>> a = np.array(['a', 'b', 'b', 'c', 'a'])
>>> u, indices = np.unique(a, return_index=True)
>>> u
array(['a', 'b', 'c'], dtype='<U1')
>>> indices
array([0, 1, 3])
>>> a[indices]
array(['a', 'b', 'c'], dtype='<U1')

return_inverse记录恢复原状所需要的索引值 

>>> a = np.array([1, 2, 6, 4, 2, 3, 2])
>>> u, indices = np.unique(a, return_inverse=True)
>>> u
array([1, 2, 3, 4, 6])
>>> indices
array([0, 1, 4, ..., 1, 2, 1])
>>> u[indices]
array([1, 2, 6, ..., 2, 3, 2])

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值