为什么ndarray允许浮点索引

Che*_*eng 8 python numpy

我可以知道为什么ndarray允许浮点索引访问,这意味着什么?

>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)

wed*_*edi 6

不再允许在ndarray中使用浮点索引,并且从版本1.12开始引发错误.

IndexError: only integers, slices (`:`), ellipsis (`...`),
    numpy.newaxis (`None`) and integer or boolean arrays are valid indices
Run Code Online (Sandbox Code Playgroud)

使用浮点数进行索引会引发 IndexError,例如,[0,0.0].(见1.11发行说明)

使用浮点数进行索引会引发 IndexError,例如a [0,0.0].(见1.12发行说明)

(我的重点)


wim*_*wim 5

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

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

作为边注,非整数切片表示法(甚至在切片复数)可以在其索引技巧类使用r_c_,例如:

>>>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.  ]])
Run Code Online (Sandbox Code Playgroud)