python - 获取 numpy 中出现次数最少的值的索引

标签 python numpy

我有一个返回整数标签的 numpy 数组的函数,例如:

labels_array = numpy.array([0, 0, 1, 1, 0, 1, 2, 3, 0, 2, 3,])

标签总是从 0 开始连续运行。

我的目标是找到 labels_array 中出现次数最少的标签索引。如果 labels_array 中有几个标签满足那个条件,那么我想得到所有对应的索引。对于上面的例子,我会得到

result= [6, 7, 9, 10]

不仅仅是[6]

目前我计算每个标 checkout 现的次数,然后得到出现次数最少的标签的索引。

occurrencePerLabel = numpy.bincount(labels_array)
labels = numpy.where(occurrencePerLabel == occurrencePerLabel.min())

现在我有

labels = (array([2, 3]),)

告诉我 2 和 3 是 labels_array 中出现次数最少的标签

接下来,我需要获取 labels_array 为 2 或 3 的索引,这正是我要查找的结果。基本上我在寻找类似的东西

labels_array.index(labels_array == labels)

如何使用 numpy 执行此操作?

最佳答案

>>> np.where(np.in1d(labels_array, [2, 3]))[0]
array([ 6,  7,  9, 10])

关于python - 获取 numpy 中出现次数最少的值的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31079457/

相关文章:

python - 在 numpy 中从单个 block 创建 block 矩阵的更好方法?

python - Pygame 绘图旋转 90 度

python - 如何在 AI 平台培训中将 pandas-gbq 与 BigQuery Storage API 结合使用?

python - Sklearn MLPRegressor 中的 RandomGridSearchCV 错误

python - 如何将不同维度的多个分类输入变量用于随机森林回归模型?

python - Numpy:这段代码彼此有何不同?

python - 如何连接 Pandas 中包含列表(系列)的两列

python - 如何在 Android 上的 ASE 中使用 Python 获取设备特定的 UID?

Python 数据帧到 SQL 数字正在四舍五入

python - FormWizard 中带有 MultiValueField 的外键字段与另一个外键