首页 > 解决方案 > 编写一个在python中找到一维数组中出现频率最高的值的方法

问题描述

我在 python 中使用 Counter 和 Union 尝试了一些方法,但我没有得到解决方案。

当我运行代码时,我得到了TypeError: '>=' not supported between instances of 'numpy. ndarray' and 'int'错误。

我试过了

import numpy as np
from typing import Union
from collections import Counter

def most_frequent_val(array:np.ndarray) -> Union[int,float,str]:
  counts = Counter()
  counts.most_common(array)

我的输入是一个数组

inps =np.array(["a","b","c","d","a","a","b","c","e","e","a"])

我也用过print(np.bincount(x).argmax()),但是没有用。

标签: pythonpython-3.xnumpy

解决方案


试试这个怎么样

import numpy as np
x = np.random.randint(0, 10, 40)
print("Original array:")
print(x)
print("Most frequent value in the above array:")
print(np.bincount(x).argmax())

推荐阅读