getting the opposite diagonal of a numpy array

匿名 (未验证) 提交于 2019-12-03 01:47:02

问题:

So in numpy arrays there is the built in function for getting the diagonal indices, but I can't seem to figure out how to get the diagonal starting from the top right rather than top left.

This is the normal code to get starting from the top left:

>>> import numpy as np >>> array = np.arange(25).reshape(5,5) >>> diagonal = np.diag_indices(5) >>> array array([[ 0,  1,  2,  3,  4],    [ 5,  6,  7,  8,  9],    [10, 11, 12, 13, 14],    [15, 16, 17, 18, 19],    [20, 21, 22, 23, 24]]) >>> array[diagonal] array([ 0,  6, 12, 18, 24]) 

so what do I use if I want it to return:

array([ 4,  8, 12, 16, 20]) 

回答1:

There is

In [47]: np.diag(np.fliplr(array)) Out[47]: array([ 4,  8, 12, 16, 20]) 

or

In [48]: np.diag(np.rot90(array)) Out[48]: array([ 4,  8, 12, 16, 20]) 

Of the two, np.diag(np.fliplr(array)) is faster:

In [50]: %timeit np.diag(np.fliplr(array)) 100000 loops, best of 3: 4.29 us per loop  In [51]: %timeit np.diag(np.rot90(array)) 100000 loops, best of 3: 6.09 us per loop 


回答2:

Here are two ideas:

step = len(array) - 1  # This will make a copy array.flat[step:-step:step]  # This will make a veiw array.ravel()[step:-step:step] 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!