在Python numpy ndarray中获取角值 [英] Get corner values in Python numpy ndarray

查看:161
本文介绍了在Python numpy ndarray中获取角值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问numpy ndarray的角值.对于方法论,我绝对感到困惑.任何帮助将不胜感激.

I'm trying to access the corner values of a numpy ndarray. I'm absolutely stumped as for methodology. Any help would be greatly appreciated.

例如,从下面的数组中,我想要一个返回值array([1,0,0,5])或array([[1,0],[0,5]]).

For example, from the below array I'd like a return value of array([1,0,0,5]) or array([[1,0],[0,5]]).

array([[ 1.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  5.],
       [ 0.,  0.,  5.,  5.]])

推荐答案

要在答案中添加变化,您可以查看以下边角项目的视图(而不是副本):

To add variety to the answers, you can get a view (not a copy) of the corner items doing:

corners = a[::a.shape[0]-1, ::a.shape[1]-1]

或者,对于一般的n维数组:

Or, for a generic n-dimensional array:

corners = a[tuple(slice(None, None, j-1) for j in a.shape)]

这样做,您可以通过修改视图来修改原始数组:

Doing this, you can modify the original array by modifying the view:

>>> a = np.arange(9).reshape(3, 3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> corners = a[tuple(slice(None, None, j-1) for j in a.shape)]
>>> corners
array([[0, 2],
       [6, 8]])
>>> corners += 1
>>> a
array([[1, 1, 3],
       [3, 4, 5],
       [7, 7, 9]])

编辑啊,您想要一个平面角值列表...通常无法通过视图实现,因此@IanH的答案就是您想要的.

EDIT Ah, you want a flat list of corner values... That cannot in general be achieved with a view, so @IanH's answer is what you are looking for.

这篇关于在Python numpy ndarray中获取角值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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