4

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!

jpp
  • 159,742
  • 34
  • 281
  • 339
user2379123
  • 85
  • 3
  • 14

1 Answers1

3

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]))
jpp
  • 159,742
  • 34
  • 281
  • 339