gpt4 book ai didi

python - 使用二维数组索引一维 Numpy 数组

转载 作者:行者123 更新时间:2023-11-28 19:03:57 25 4
gpt4 key购买 nike

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

# 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]])

最佳答案

What array array indexing rule applies to following code?

这就是 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.

关于python - 使用二维数组索引一维 Numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49230302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com