简体   繁体   中英

Return most common value (mode) of a matrix / array

Simple question: How do I get the most common value of a matrix?

A matrix is a specialized 2-D array that retains its 2-D nature through operations.

This is a snippet of my whole implementation, so I've decided to show you only the important parts referring to my main question:

import numpy as np
...
from src.labelHandler import LabelHandler
from collections import Counter

def viewData(filePathList, labelHandler=None):
...
    c = Counter(a)       #(1)
    print(c)             #(2)
    b = np.argmax(c)     #(3)
    print(b)             #(4)
...

The output would be:

{0.3: [(0, 0, 0), (0, 10, 0), (0, 11, 0), ...], 0.2: [(0, 18, 0), ...]}
Counter({0.3: 7435, 0.2: 6633, ...})
0

This is also a snippet from my whole output.

The important line is the last one with the 0. The problem seems to be line (3).

b = np.argmax(c)

It just prints out the position of my largest value which is in index 0. But I would like to get back the float value itself instead of the index.

How do I solve this problem?

Thanks in advance!

You can use scipy.stats together with np.array.ravel() to flatten the array. This gives you both the mode and the count.

import numpy as np
from scipy import stats

A = np.random.randint(0, 9, (10, 10))

res = stats.mode(A.ravel())

# ModeResult(mode=array([4]), count=array([19]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM