得到一个numpy数组的对角线 [英] getting the opposite diagonal of a numpy array

查看:769
本文介绍了得到一个numpy数组的对角线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此在numpy数组中,有用于获取对角线索引的内置函数,但是我似乎无法弄清楚如何从右上角而不是左上角开始获取对角线.

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])

推荐答案

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

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

两者中的np.diag(np.fliplr(array))更快:

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

这篇关于得到一个numpy数组的对角线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆