【问题标题】:Showing wrong axis in 2D array when value is out of range当值超出范围时,在二维数组中显示错误的轴
【发布时间】:2021-11-25 11:35:50
【问题描述】:

我有一个二维数组 (row*column)row 表示axis0,column 表示aixs1。

示例:

a=np.array([[10,20,30],[40,50,60]])

现在,当我尝试访问该值时(超出轴 0 的范围),我正在低于正确的异常。

print(a[-3][-1])

    IndexError: index -3 is out of bounds for `axis 0` with size 2

注意:当我沿着轴 1 尝试时,它仍然显示相同的 axis0,应该是 axis1

print(a[-2][5])
IndexError: index 5 is out of bounds for axis 0 with size 3

【问题讨论】:

    标签: python numpy numpy-ndarray numpy-slicing numpy-indexing


    【解决方案1】:

    这是因为您首先将a 子集化为一维向量。

    >>> a[-2]
    array([10, 20, 30])
    
    >>> np.array([10, 20, 30])[5]
    IndexError: index 5 is out of bounds for axis 0 with size 3
    

    但是,如果您同时对两个维度进行切片,则会得到预期的错误:

    >>> a[-2, 5]
    IndexError: index 5 is out of bounds for axis 1 with size 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多