Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find most frequent string element in numpy ndarray?

Is their any way to find most frequent string element in numpy ndarray?

A= numpy.array(['a','b','c']['d','d','e']])


result should be 'd'
like image 501
2964502 Avatar asked Nov 11 '13 14:11

2964502


People also ask

How do I find the most common number in an array Python?

Make use of Python Counter which returns count of each element in the list. Thus, we simply find the most common element by using most_common() method.

What is the difference between NumPy Ndarray and array?

array is just a convenience function to create an ndarray ; it is not a class itself. You can also create an array using numpy. ndarray , but it is not the recommended way. From the docstring of numpy.


2 Answers

If you want a numpy answer 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 counts this will simply take the first from the unique array.

With this you can also easily sort by element count like so:

>>> maxsort = counts.argsort()[::-1]
>>> (unique[maxsort],counts[maxsort])
(array(['d', 'e', 'c', 'b', 'a'],
      dtype='|S1'), array([2, 1, 1, 1, 1]))
like image 171
Daniel Avatar answered Sep 22 '22 15:09

Daniel


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 the 'd' is left as an exercise for the reader.

like image 43
NPE Avatar answered Sep 20 '22 15:09

NPE