0

Please can someone tell me how i could get the most frequent/modal array out of an nested array?

So for example for:

a = np.array([[A, 8, 3, 0],[B, 8, 4, 0],[A, 8, 3, 0]])

The result should be [A, 8, 3, 0] with count 2.

I did my research on that problem, but only found solutions which compare one value of one dimension and not the whole arrays.

And is it possible to get the 2nd and 3rd most frequent array too?

Thank you in advance,

Greetings :)

Swift
  • 1,663
  • 1
  • 10
  • 21
QWERASDFYXCV
  • 245
  • 1
  • 6
  • 15
  • Your example is not a correct / complete (numpy) array literal. As for the actual problem & solution, this question has already been asked and answered for example in [find the most frequent number in a numpy array](https://stackoverflow.com/questions/6252280/find-the-most-frequent-number-in-a-numpy-vector). Use a `collections.Counter` and convert your nested array to a nested tuple beforehand. – elemakil Oct 04 '18 at 21:00

2 Answers2

0

If you don't care about the order of the lists, then you can use set comparisons to find the most common element just as you would do if you had a list of integers.

L = [['A', 8, 3, 0],['B', 8, 4, 0],['A', 8, 3, 0]]
counter = 0
set = L[0]
for i in L:
    amount_times = L.count(i)
    if amount_times > counter:
        counter = amount_times
        set = i

print (set)
print (counter)`
Abhishek Patel
  • 587
  • 2
  • 8
  • 25
0

Using pandas

import pandas as pd
a = np.array([['A', 8, 3, 0],['B', 8, 4, 0],['A', 8, 3, 0]])
df=pd.DataFrame(a)
df=df.reset_index().groupby([0,1,2,3]).count().sort_values('index',ascending=False).reset_index()

np.array(df.iloc[0,0:4])

If you print you can find all the frequencies. HTH

mad_
  • 8,121
  • 2
  • 25
  • 40