numpy.unique() 简单用法

numpy.unique() 函数接受一个数组,去除其中重复元素,并按元素由小到大返回一个新的无元素重复的元组或者列表。

尝试用参数 return_counts 解决一个小问题。

# coding: utf-8
import numpy as np

# 任务: 统计 a 中元素个数, 找出出现次数最多的元素
a = np.array([1, 1, 1, 3, 3, 2, 2, 2, 2, 4, 5, 5])

# numpy.unique() 测试
b = np.unique(a)
print(b)

# 使用 return_counts=True 统计元素重复次数
b, count = np.unique(a, return_counts=True)
print(b, count)

# 使用 zip 将元素和其对应次数打包成一个个元组, 返回元组的列表
zipped = zip(b, count)
# for i, counts in zipped:
#     print("%d: %d" % (i, counts))  # 这里打印zipped出来,
#                                    # 下面 max()会报
#                                    # ValueError: max() arg is an empty sequence
#                                    # 不知道为什么 >_<

# 使用 max() 函数找出出现次数最多的元素
target = max(zipped, key=lambda x: x[1])
print(target)

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值