为什么ndarray允许浮点索引 [英] Why ndarray allow floating point index

查看:74
本文介绍了为什么ndarray允许浮点索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以知道为什么ndarray允许访问浮点索引吗?

May I know why ndarray allows floating point index accessing, and what does that mean?

>>> wk1 = numpy.arange(10)
>>> wk1[1:2.8]
array([1])
>>> wk1 = [1,2,3,4,5,6,7,8,9,10]
>>> wk1[1:2.8]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: slice indices must be integers or None or have an __index__ method
>>>

推荐答案

这可能很有用,我想知道为什么其他类像numpy那样做.

This can be useful, and I wonder why other classes don't do it the way numpy does.

当我注意到这是一个特别有用的时间时,如果您的numpy数组是一个图像,并且您有一个鼠标单击事件处理程序,可以为您提供event.xdataevent.ydata浮动,那么您仍然可以使用切片的感兴趣区域,而不必将其转换为像素坐标.例如,假设您正在通过单击和拖动选择来裁剪图像或放大图像-图像中的鼠标位置通常位于子像素坐标上,除非特殊情况下以1:1比例显示图像.

One particularly helpful time when I've noticed this is if your numpy array is an image, and you have an event handler for mouse clicks which give you event.xdata and event.ydata as floats, then you can still get a region of interest using the slices without having to convert them to pixel coordinates. For example, suppose you were cropping an image or zooming in an image by clicking and dragging a selection - the mouse position in the image will generally be on sub-pixel coordinates except for the special case where the image is displayed 1:1 scale.

请注意,非整数切片符号(甚至切片中的复数)可以在其索引技巧类r_c_中使用,例如:

As a side note, non-integer slice notation (even complex numbers in slices) can be used in their index tricks classes r_ and c_, for example:

>>>np.r_[0:3:0.1]
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ,
        1.1,  1.2,  1.3,  1.4,  1.5,  1.6,  1.7,  1.8,  1.9,  2. ,  2.1,
        2.2,  2.3,  2.4,  2.5,  2.6,  2.7,  2.8,  2.9])

>>>np.c_[-1:1:9j]
array([[-1.  ],
       [-0.75],
       [-0.5 ],
       [-0.25],
       [ 0.  ],
       [ 0.25],
       [ 0.5 ],
       [ 0.75],
       [ 1.  ]])

这篇关于为什么ndarray允许浮点索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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