如何找到 numpy ndarray 中最常见的字符串元素?

2024-03-26

他们有什么方法可以找到 numpy ndarray 中最常见的字符串元素吗?

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


result should be 'd'

如果你想要一个 numpy 答案,你可以使用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 array.

有了这个,您还可以轻松地按元素计数排序,如下所示:

>>> maxsort = counts.argsort()[::-1]
>>> (unique[maxsort],counts[maxsort])
(array(['d', 'e', 'c', 'b', 'a'],
      dtype='|S1'), array([2, 1, 1, 1, 1]))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何找到 numpy ndarray 中最常见的字符串元素? 的相关文章

随机推荐