如何在numpy ndarray中找到最常使用的字符串元素? [英] how to find most frequent string element in numpy ndarray?
本文介绍了如何在numpy ndarray中找到最常使用的字符串元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
他们有什么办法在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'
推荐答案
如果您想要一个小数答案,则可以使用np.unique
:
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)
尽管如果有两个元素具有相同的计数,则这将只是从unique
数组中获取第一个元素.
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]))
这篇关于如何在numpy ndarray中找到最常使用的字符串元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文