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 :)

1
  • 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. Use a collections.Counter and convert your nested array to a nested tuple beforehand. Commented Oct 4, 2018 at 21:00

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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)`

2 Comments

This is a solution using the built in lists for python. A more specific answer for numpy arrays would be using the answer @mad_ provided
Ok i will try this out tomorrow but that should work thank you :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.