2017-01-09 14 views
3

私は2次元配列を持っています。そこから、その行とその列の両方の上位2つの値にあるすべての要素のインデックスを取得したいと思います。例えば、以下の配列を指定 -要素loactionsを見つける方法numpy配列

r = np.random.rand(5,5) 
>>> r 
array([[ 0.89771084, 0.84415435, 0.81601728, 0.42322215, 0.78240944], 
     [ 0.84490939, 0.53644975, 0.3506268 , 0.98212093, 0.76426087], 
     [ 0.254155 , 0.12818165, 0.82656036, 0.97441244, 0.58597015], 
     [ 0.50566688, 0.67774518, 0.58434845, 0.5204808 , 0.9225643 ], 
     [ 0.73930611, 0.31890204, 0.47691016, 0.28034347, 0.57832287]]) 

必要が出力される - それの列の二番目に大きい要素であるが、それは第三位であるため

[[0,0], 
[1,0], 
[0,1], 
[3,1], 
[2,2], 
[1,3], 
[2,3], 
[3,4]] 

注意[0,2]は、除外されていますそれの行の要素。

+1

ありません。 'argsort'を試してください。 – Divakar

+0

@Divakar明確ではないものはありますか? – proton

+0

スライス 'rcols [3:5]'は何を意味していますか?与えられたサンプルに関して、期待される出力は何ですか? – Divakar

答えて

1

コメントに示唆されているように、argsortがキーです。これはソートされた要素のインデックスを提供します。 argsortを2回実行すると、ランクが得られます。 (私は練習として残してランクを得るより効率的な方法があります)

次に、行と列に沿ってランクを使用して、ランクと列の両方について上位2にある要素を識別します。

実装例:十分に明確

import numpy as np 

r = np.array([[ 0.89771084, 0.84415435, 0.81601728, 0.42322215, 0.78240944], 
       [ 0.84490939, 0.53644975, 0.3506268 , 0.98212093, 0.76426087], 
       [ 0.254155 , 0.12818165, 0.82656036, 0.97441244, 0.58597015], 
       [ 0.50566688, 0.67774518, 0.58434845, 0.5204808 , 0.9225643 ], 
       [ 0.73930611, 0.31890204, 0.47691016, 0.28034347, 0.57832287]]) 

# indices of elements in descending order 
col_order = np.argsort(r, axis=0)[::-1, :] 
row_order = np.argsort(r, axis=1)[:, ::-1] 

# sorting the indices gives the rank (0=highest element, 4=lowest element) 
col_rank = np.argsort(col_order, axis=0) 
row_rank = np.argsort(row_order, axis=1) 

# mark top n elements in each row and column 
n = 2 
col_top_n = col_rank < n 
row_top_n = row_rank < n 

# mark elements that are in the nop n of BOTH, a row and a column 
both_top_n = np.logical_and(row_top_n, col_top_n) 

# get indices of marked elements 
row_indices, col_indices = np.nonzero(both_top_n) 

print('The following elements are in the top {} of both their rows and columns:'.format(n)) 
for row, column in zip(row_indices, col_indices): 
    print('row: {}, column: {}, value: {}'.format(row, column, r[row, column])) 
関連する問題