【问题标题】:numpy: find the count of each unique element in an arraynumpy:查找数组中每个唯一元素的计数
【发布时间】:2015-03-07 15:16:06
【问题描述】:

我有一个包含许多重复元素的数组,我想找到重复次数最多的非零元素的计数和值。我有点让它工作,但我不确定这是否是在 python 中正确的方法。

一些测试代码:

import numpy as np

x = np.array([0, 0, 0, 10, 10, 10, 10, 10])

l = list()
for i in np.unique(x):
    l.extend((np.count_nonzero(x[x==i]),))

maximum_times = np.max(l)

这告诉我最大元素重复的次数,但它没有告诉我那个元素是什么,也许使用 for 循环不是一个好主意,但我想不出任何其他 pythonic 解决方案。

【问题讨论】:

  • Numpy 版本?在 1.9 中,您可以将 return_counts=True 传递给 unique()

标签: python search numpy


【解决方案1】:

正如 Ashwini 所说,您可以为此使用 return_counts=True

x = np.array([0, 0, 0, 10, 10, 10, 10, 10])

elements, repeats = np.unique(x, return_counts=True)
index = repeats.argmax()
elem = elements[index]

print "Max elem is " + str(elem) + " with " + str(repeats[index]) + " repetitions."

【讨论】:

  • 这比我的尝试优雅得多。谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-03-15
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-14
  • 1970-01-01
相关资源
最近更新 更多