我尝试使用scipy.stats
模式查找最常用的值。我的矩阵包含很多零,所以这总是模式。
例如,如果我的矩阵如下所示:
array = np.array([[0, 0, 3, 2, 0, 0],
[5, 2, 1, 2, 6, 7],
[0, 0, 2, 4, 0, 0]])
我希望返回2
的值。
答案 0 :(得分:5)
尝试collections.Counter
:
import numpy as np
from collections import Counter
a = np.array(
[[0, 0, 3, 2, 0, 0],
[5, 2, 1, 2, 6, 7],
[0, 0, 2, 4, 0, 0]]
)
ctr = Counter(a.ravel())
second_most_common_value, its_frequency = ctr.most_common(2)[1]
答案 1 :(得分:0)
正如一些评论中提到的,你可能会谈到numpy数组。
在这种情况下,屏蔽您想要避免的值非常简单:
import numpy as np
from scipy.stats import mode
array = np.array([[0, 0, 3, 2, 0, 0],
[5, 2, 1, 2, 6, 7],
[0, 0, 2, 4, 0, 0]])
flat_non_zero = array[np.nonzero(array)]
mode(flat_non_zero)
返回(array([2]), array([ 4.]))
表示出现最多的值是2,它出现4次(有关详细信息,请参阅doc)。因此,如果您只想获得2,则只需要获取模式返回值的第一个索引:mode(flat_non_zero)[0][0]
编辑:如果你想从数组中过滤另一个特定值x而不是零,你可以使用array[array != x]
答案 2 :(得分:0)
original_list = [1, 2, 3, 1, 2, 5, 6, 7, 8] #original list
noDuplicates = list(set(t)) #creates a list of all the unique numbers of the original list
most_common = [noDuplicates[0], original_list.count(noDuplicates[0])] #initializes most_most common to
#the first value and count so we have something to start with
for number in noDuplicates: #loops through the unique numbers
if number != 0: #makes sure that we do not check 0
count = original_list.count(number) #checks how many times that unique number appears in the original list
if count > most_common[1] #if the count is greater than the most_common count
most_common = [number, count] #resets most_common to the current number and count
print(str(most_common[0]) + " is listed " + str(most_common[1]) + "times!")
这将遍历您的列表并查找最常用的数字,并使用原始列表中的出现次数进行打印。