首页 > 解决方案 > 在numpy中,如何创建源数组中元素的索引数组,因为它们在目标数组中找到?

问题描述

我确信这个问题已经在某个地方得到了回答,但我就是找不到要寻找的词。

我有这两个数组:

import numpy as np

src = np.array([[8, 1],
                [2, 4]]) 

dst = np.array([[1, 4],
                [8, 2]]) 

我想得到这个数组:

indices = (np.array([[1, 0],
                     [1, 0]]),
           np.array([[0, 0],
                     [1, 1]]))

这样dst[indices]我就明白了src

有任何想法吗?此外,我正在寻找什么样的操作?这样我以后可以自己搜索更多。

标签: pythonnumpy

解决方案


这是我认为是“直接”的方式:

# find order of src and dst
so = src.ravel().argsort()
do = dst.ravel().argsort()
# allocate combined map
tot = np.empty_like(src)

# next line is all you need to remember
tot.ravel()[so] = do

# go back to 2D indexing
indices = np.unravel_index(tot,dst.shape)

# check
dst[indices]
# array([[8, 1],
#        [2, 4]])

indices
# (array([[1, 0],
#         [1, 0]]), array([[0, 0],
#         [1, 1]]))

推荐阅读