python - 如何在Python中找到最小索引并通过最少使用的索引打破平局?

标签 python numpy

我有一个如下所示的 numpy 数组:

A = np.array([[1, 1, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 5, 1, 1, 1],
              [1, 1, 1, 1, 3, 3, 1, 1],
              [1, 1, 1, 1, 1, 1, 2, 1],
              [1, 1, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 1, 4, 1, 1]])

我正在寻找每列中的最小索引。我使用 numpy.argmin 找到了这个如下:

I = np.zeros(A.shape[1], dtype=np.int64)
for j in range(A.shape[1]):
    I[j] = np.argmin(A[:, j])

这给了我I = [0, 0, 0, 0, 0, 0, 0, 0] 。由于存在联系,我可以获得以下信息:I = [0, 1, 2, 3, 4, 0, 5, 1] ,其中我通过最少使用的索引(来自之前的索引)来打破联系。

更多详细信息:

  • 对于j=0 ,我们有np.argmin(A[:, 0]) in [0, 1, 2, 3, 4, 5]比如说,我们选择 np.argmin(A[:, 0]) = 0
  • 对于j=1 ,我们有np.argmin(A[:, 1]) in [0, 1, 2, 3, 4, 5]我们必须从[1, 2, 3, 4, 5]中选择最小索引因为这些索引是最少使用的(我们已经选择 np.argmin(A[:, 0]) = 0 作为 j=0 )。比如说,我们选择np.argmin(A[:, 1])=1
  • 对于j=2 ,我们有np.argmin(A[:, 2]) in [0, 1, 2, 3, 4, 5]我们必须从[2, 3, 4, 5]中选择最小索引因为这些索引是最少使用的。
  • 我们就这样继续下去...
  • 对于j=5 ,我们有np.argmin(A[:, 5]) in [0, 1, 3, 4]我们必须从[0, 1, 3, 4]中选择最小索引因为这些索引是最少使用的。假设我们选择np.argmin(A[:, 5])=0 .
  • 对于j=6 ,我们有np.argmin(A[:, 6]) in [0, 1, 2, 4, 5]我们必须从[5]中进行选择因为这些索引是最少使用的。我们选择np.argmin(A[:, 6])=5 .
  • 对于j=7 ,我们有np.argmin(A[:, 7]) in [0, 1, 2, 3, 4, 5]我们必须从[1, 2, 3, 4, 5]中进行选择因为这些索引是最少使用的。假设我们选择np.argmin(A[:, 7])=1 .

我希望这是清楚的。我的问题是如何在 Python 中找到最小索引并通过最少使用的索引打破联系?

最佳答案

您可以使用min结合字典来保存每个索引的计数:

import numpy as np

A = np.array([[1, 1, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 5, 1, 1, 1],
              [1, 1, 1, 1, 3, 3, 1, 1],
              [1, 1, 1, 1, 1, 1, 2, 1],
              [1, 1, 1, 1, 1, 1, 1, 1],
              [1, 1, 1, 1, 1, 4, 1, 1]])

counts = {}
I = np.zeros(A.shape[1], dtype=np.int64)
for j in range(A.shape[1]):
    _, _, i = min([(v, counts.get(i, 0), i) for i, v in enumerate(A[:, j])])
    counts[i] = counts.get(i, 0) + 1
    I[j] = i

print(I)

输出

[0 1 2 3 4 0 5 1]

这个想法是创建以下键:(value, count of index, index),然后使用元组的正常比较,因此如果值相等,则计数较少的值将选择相应的索引,如果两个计数相等,则选择索引较低的一个。

关于python - 如何在Python中找到最小索引并通过最少使用的索引打破平局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53162173/

相关文章:

python - 从二进制文件中提取文本(在Windows 7上使用Python 2.7)

python - 在 Python 中实现复数比较?

python - 如何减少获取帧时的CPU使用率

python - 连接用户登录 View ,表单与由 Django 管理员创建的预先存在的用户

python - Python 中子进程 PIPE 的非阻塞读取,一次一个字节

python - 将数组的字符串表示形式转换为 python 中的 numpy 数组

Python numpy 按字符串列的值拆分 csv 文件

python - 梯度下降的 self 实现与 SciPy Minimize 的比较

Python:在for循环中追加数组列

python - 从子数组中的 numpy 二维数组中提取相交数组的索引