在2d数组中找到前'n'个元素的2d坐标(行,col),然后使用这些坐标使用python对其他数组进行操作?

时间:2019-04-12 03:56:39

标签: python arrays image numpy multidimensional-array

请参见以下示例,以更好地理解我的问题。

假设它们是两个数组A和B:

A=array([[1,2,3,4],
         [5,6,7,8],
         [9,10,11,12]])

B=array([[3,4,12,2],
         [5,11,1,6],
         [9,10,7,8]])

在B中找到其中前5个元素(12、11、10、9、8)的坐标。

预期的输出1:

coordinates=(0,2)
            (1,1)
            (2,1)
            (2,0)
            (2,3)

现在,我想将位置在坐标(0,2),(1,1),(2,1),(2,0),(2,3)中的元素乘以10。 / p>

则预期输出2将为:

[30,60,100,90,120]

我是python编码的新手。请帮助我达到要求。

3 个答案:

答案 0 :(得分:1)

numpy.array.ravelnumpy.array.argsort一起使用:

A.ravel()[B.ravel().argsort()[-5:][::-1]] * 10

输出:

array([ 30,  60, 100,  90, 120])

答案 1 :(得分:1)

对于大型数组,argpartiton将更有效:

A=np.random.rand(100,100)
B=np.random.rand(100,100)

%timeit A.ravel()[np.argpartition(B,B.size-5,None)[-5:]] * 10
459 µs ± 37.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit A.ravel()[B.ravel().argsort()[-5:][::-1]] * 10
2.85 ms ± 34.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

答案 2 :(得分:0)

代码以获取预期的输出1

C=(B.ravel().argsort()[-5:][::-1])
cord=(np.unravel_index(C, B.shape))

输出

(array([0, 1, 2, 2, 2], dtype=int64), array([2, 1, 1, 0, 3], dtype=int64))

## here 1st array gives the row coordinates and 2nd array gives the column coordinates of top 5 elements in B. In order.