我有一个如下所示的 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/