(Python)具有优先数组的两个数组之间的映射

2024-03-29 09:20:44 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个源数组

src = np.random.rand(320,240)

和索引数组

idx = np.indices(src.shape).reshape(2, -1)
np.random.shuffle(idx.T)

我们可以将src中的线性索引i映射到目标数组dst中的二维索引idx[:,i]

dst = np.empty_like(src)
dst[tuple(idx)] = src.ravel()

这将在Python: Mapping between two arrays with an index array中讨论

但是,如果此映射不是1对1的,即src中的多个条目映射到dst中的同一条目,according to the docs则未指定哪些源条目将写入dst

For advanced assignments, there is in general no guarantee for the iteration order. This means that if an element is set more than once, it is not possible to predict the final result.

如果我们另外得到一个优先数组

p = np.random.rand(*src.shape)

我们如何使用p来消除这种情况,即根据p编写优先级最高的条目?你知道吗


Tags: thetosrcanisnp条目random
1条回答
网友
1楼 · 发布于 2024-03-29 09:20:44

这里有一个使用稀疏矩阵进行排序的方法(它有很大的开销,但比argsort的伸缩性更好,可能是因为它使用了一些类似基数排序的方法(?)。没有优先级的重复索引显式设置为-1。我们使目标数组的一个单元太大,多余的单元充当垃圾桶。你知道吗

import numpy as np
from scipy import sparse

N = 2
idx = np.random.randint(0, N, (2, N, N))
prec = np.random.random((N, N))
src = np.arange(N*N).reshape(N, N)

def f_sparse(idx, prec, src):
    idx = np.ravel_multi_index(idx, src.shape).ravel()
    sp = sparse.csr_matrix((prec.ravel(), idx, np.arange(idx.size+1)),
                           (idx.size, idx.size)).tocsc()
    top = sp.indptr.argmax()
    mx = np.repeat(np.maximum.reduceat(sp.data, sp.indptr[:top]),
                   np.diff(sp.indptr[:top+1]))
    res = idx.copy()
    res[sp.indices[sp.data != mx]] = -1

    dst = np.full((idx.size + 1,), np.nan)
    dst[res] = src.ravel()
    return dst[:-1].reshape(src.shape)

print(idx)
print(prec)
print(src)
print(f_sparse(idx, prec, src))

运行示例:

[[[1 0]
  [1 0]]

 [[0 1]
  [0 0]]]
[[0.90995366 0.92095225]
 [0.60997092 0.84092015]]
[[0 1]
 [2 3]]
[[ 3.  1.]
 [ 0. nan]]

相关问题 更多 >