Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python numpy:查找数组中每个唯一元素的计数_Python_Search_Numpy - Fatal编程技术网

Python numpy:查找数组中每个唯一元素的计数

Python numpy:查找数组中每个唯一元素的计数,python,search,numpy,Python,Search,Numpy,我有一个数组,其中有许多重复元素,我想找到重复次数最多的非零元素的计数和值。我有点让它工作,但我不确定这是否是在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)

我有一个数组,其中有许多重复元素,我想找到重复次数最多的非零元素的计数和值。我有点让它工作,但我不确定这是否是在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)

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

正如Ashwini所指出的,您可以使用
return\u 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."

正如Ashwini所指出的,您可以为此使用
return\u 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."

Numpy版本?在1.9中,您可以将
return\u counts=True
传递到
unique()
。Numpy版本?在1.9中,您可以将
return\u counts=True
传递到
unique()
。这比我的尝试要优雅得多。谢谢。这比我试的要优雅得多。谢谢