5
A
回答
13
是,Python的collections.Counter对发现的最常见的元素直接支持:
>>> from collections import Counter
>>> Counter('abracadbra').most_common(2)
[('a', 4), ('r', 2)]
>>> Counter([1,2,1,3,3,4]).most_common(2)
[(1, 2), (3, 2)]
随着numpy的,你可能要开始与histogram() function或bincount() function。
随着scipy,你可以搜索mstats.mode模态元素。
2
pandas
模块也可能对此有所帮助。 pandas
是一个用于python的整洁的数据分析软件包,同时也支持这个问题。
import pandas as pd
arr = np.array([1,2,1,3,3,4])
arr_df = pd.Series(arr)
value_counts = arr_df.value_counts()
most_frequent = value_counts.max()
这将返回
> most_frequent
2
0
这适用于任何类型的工作,整数与否,返回始终是一个numpy的数组:
def most_common(a, n=1) :
if a.dtype.kind not in 'bui':
items, _ = np.unique(a, return_inverse=True)
else:
items, _ = None, a
counts = np.bincount(_)
idx = np.argsort(counts)[::-1][:n]
return idx.astype(a.dtype) if items is None else items[idx]
>>> a = np.fromiter('abracadabra', dtype='S1')
>>> most_common(a, 2)
array(['a', 'r'],
dtype='|S1')
>>> a = np.random.randint(10, size=100)
>>> a
array([0, 0, 0, 9, 3, 9, 1, 2, 6, 3, 0, 4, 3, 2, 4, 7, 2, 8, 8, 2, 9, 7, 0,
3, 5, 2, 5, 0, 4, 2, 4, 7, 8, 5, 4, 0, 1, 6, 1, 0, 2, 0, 5, 1, 3, 8,
8, 6, 3, 5, 4, 3, 3, 5, 0, 7, 3, 0, 2, 5, 4, 2, 4, 2, 8, 1, 4, 4, 7,
4, 4, 3, 7, 4, 0, 1, 0, 8, 8, 1, 1, 2, 1, 4, 2, 5, 1, 0, 7, 2, 0, 0,
0, 8, 9, 9, 8, 1, 3, 8])
>>> most_common(a, 5)
array([0, 4, 2, 8, 3])
相关问题
- 1. 函数中是否可以有函数?
- 2. python是否有“causes_exception()”函数?
- 3. 是否有Cells()。Formula函数?
- 4. 是否有WinAPI函数'ExistFile'?
- 5. python是否有soundex函数?
- 6. 是否有php sendmail()函数?
- 7. idris是否有模函数?
- 8. Django/Python中是否有dump()函数?
- 9. 在Python 3中是否有'foreach'函数?
- 10. wso2esb中是否有替换函数?
- 11. 在ActionScript中是否有div()函数?
- 12. 斯卡拉中是否有lambda函数?
- 13. 在dlg类中是否有getdocument()函数?
- 14. 在laravel中是否有initalSetup()函数?
- 15. R函数中是否有“this”引用?
- 16. Android中是否有编译时函数?
- 17. SQLAlchemy中是否有mysql unix_timestamp函数?
- 18. jQuery中是否有onAvailable()函数?
- 19. numpy中是否有elliptictheta函数?
- 20. 函数中是否有临时表?
- 21. Oracle WebForms中是否有printf函数?
- 22. CAPL中是否有Wait()或Sleep()函数?
- 23. GQL中是否有concat函数?
- 24. Puppet中是否有`index_of`函数/方法?
- 25. opencv中是否有DWT函数?
- 26. MATLAB中是否有histo函数?
- 27. C++中是否有parallel_for的boost函数?
- 28. PHP中是否有get_method()函数?
- 29. Elixir中是否有非静态函数?
- 30. xpath中是否有分割函数?
使用'np.bincount'如果所有元素是整数。 – nye17