How to find the most frequent line item in numpy ndarray?

Is there a way to find the most common string element in numpy ndarray?

A= numpy.array(['a','b','c']['d','d','e']]) result should be 'd' 
+6
source share
2 answers

If you want a numpy response, you can use np.unique :

 >>> unique,pos = np.unique(A,return_inverse=True) #Finds all unique elements and their positions >>> counts = np.bincount(pos) #Count the number of each unique element >>> maxpos = counts.argmax() #Finds the positions of the maximum count >>> (unique[maxpos],counts[maxpos]) ('d', 2) 

Although if there are two elements with equal values, it just takes the first of the unique array.

With this, you can also easily sort by element like this:

 >>> maxsort = counts.argsort()[::-1] >>> (unique[maxsort],counts[maxsort]) (array(['d', 'e', 'c', 'b', 'a'], dtype='|S1'), array([2, 1, 1, 1, 1])) 
+10
source

Here is one way:

 >>> import numpy >>> from collections import Counter >>> A = numpy.array([['a','b','c'],['d','d','e']]) >>> Counter(A.flat).most_common(1) [('d', 2)] 

Extracting 'd' left as an exercise for the reader.

+3
source

Source: https://habr.com/ru/post/957835/


All Articles