3

在 Numpy 中,我们可以使用 2D 数组作为 1D 数组的索引吗?什么数组数组索引规则适用于以下代码?

# 1D array
arr = np.arange(10)
# array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

# 2D index 
indx = np.array([[2, 4], [6, 8]])

# 2D index in 1D array
arr[indx]

# Output of above indexing is a 2D array!
array([[2, 4],[6, 8]])
4

1 回答 1

1

什么数组数组索引规则适用于以下代码?

这就是 numpy 的高级索引的工作原理。结果数组的形状与索引数组的形状、数组的形状和传递索引的轴有关。下面是一些将 3D 数组作为索引传递给具有不同形状的数组的第一个轴的示例。

In [47]: a.shape
Out[47]: (2, 5)

In [48]: b = a[np.array([[[0],[1]],[[1],[1]]])]

In [49]: b.shape
Out[49]: (2, 2, 1, 5)

In [50]: arr.shape
Out[50]: (3, 3, 3)

In [51]: b = arr[np.array([[[0],[1]],[[1],[1]]])]

In [52]: b.shape
Out[52]: (2, 2, 1, 3, 3)

当您将不同的数组传递给不同的轴时,您会得到以下结果:

In [61]: b = arr[[[0],[2]],[[1],[0]]]

In [62]: b.shape
Out[62]: (2, 1, 3)

In [63]: arr.shape
Out[63]: (3, 3, 3)

在所有这些索引中,Numpy 将检查多项内容,首先,它检查作为索引传递的对象的类型。其次,它将索引数组的形状与数组各自轴的形状进行比较。第三,它检查结果是否产生了一个有效的 Numpy 数组。

以下是一些其他示例:

In [64]: b = arr[[[[0],[2]]],[[1],[0]]]

In [65]: b.shape
Out[65]: (1, 2, 1, 3)

In [66]: b
Out[66]: 
array([[[[ 3,  4,  5]],

        [[18, 19, 20]]]])

In [67]: b = arr[[[[0],[2]]],[1],[0]]

In [68]: b
Out[68]: 
array([[[ 3],
        [21]]])

In [69]: b = arr[[[['a'],[2]]],[1],[0]]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-69-dba030ba9787> in <module>()
----> 1 b = arr[[[['a'],[2]]],[1],[0]]

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

In [70]: b = arr[[[[0],[2]]],[1],0]

In [71]: b = arr[[[[0],[2]]],[5],0]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-71-0962012e570a> in <module>()
----> 1 b = arr[[[[0],[2]]],[5],0]

IndexError: index 5 is out of bounds for axis 1 with size 3

In [72]: 

In [72]: b = arr[[[[0],[[2]]]],[5],0]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-72-9a520b0cb30e> in <module>()
----> 1 b = arr[[[[0],[[2]]]],[5],0]

ValueError: setting an array element with a sequence.

In [73]: b = arr[[[[0],[[2]]]],[5],[0]]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-73-67187db6f452> in <module>()
----> 1 b = arr[[[[0],[[2]]]],[5],[0]]

ValueError: setting an array element with a sequence.
于 2018-03-12T08:53:27.267 回答