【问题标题】:Why ndarray allow floating point index为什么ndarray允许浮点索引
【发布时间】:2018-05-24 17:19:39
【问题描述】:

我可以知道为什么 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
>>>

【问题讨论】:

标签: python numpy


【解决方案1】:

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

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

使用浮点数进行索引会引发 IndexError,例如 a[0, 0.0]。 (See 1.11 release notes)

使用浮点数进行索引引发 IndexError,例如 a[0, 0.0]。 (See 1.12 release notes)

(我的重点)

【讨论】:

    【解决方案2】:

    这可能很有用,我想知道为什么其他类像 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.  ]])
    

    【讨论】:

    • 我同意,并且出于您所描述的原因,我也经常使用它。然而,python 的口头禅是“显式优于隐式”,所以公平地说,这可能是大多数其他 python 对象不这样做的原因。无论如何,它肯定很方便!
    【解决方案3】:

    基本上,对于 numpy 数组,int 会在任何还不是整数的输入上调用。换句话说,它向下舍入。 1.999 产生 1 等。

    例如

    import numpy as np
    x = np.arange(10)
    
    print x[1.9]
    print x[2.1]
    

    (请注意,这分别与x[1]x[2] 相同。)

    这也适用于用作索引的列表或数组:

    print x[[1.2, 3.4]]
    

    【讨论】:

      【解决方案4】:

      我无法在源代码中找到它,但是查看文档,在这种情况下传递的是一个切片对象 (http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html),看起来输入被转换为ints 在 numpy 方面。

      【讨论】:

        猜你喜欢
        • 2019-05-21
        • 2011-01-28
        • 2016-10-31
        • 2014-09-13
        • 2022-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多