为什么用括号和逗号对索引的numpy数组的行为有所不同? [英] Why does indexing numpy arrays with brackets and commas differ in behavior?
问题描述
我倾向于使用括号来索引numpy数组(矩阵),但我注意到当我想切片数组(矩阵)时我必须使用逗号表示法。为什么是这样?例如,
I tend to index numpy arrays (matrices) with brackets, but I've noticed when I want to slice an array (matrix) I must use the comma notation. Why is this? For example,
>>> x = numpy.array([[1, 2], [3, 4], [5, 6]])
>>> x
array([[1, 2],
[3, 4],
[5, 6]])
>>> x[1][1]
4 # expected behavior
>>> x[1,1]
4 # expected behavior
>>> x[:][1]
array([3, 4]) # huh?
>>> x[:,1]
array([2, 4, 6]) # expected behavior
推荐答案
这:
x[:, 1]
表示沿第一轴取 x
的所有指数,但仅限索引1沿着第二个。
means "take all indices of x
along the first axis, but only index 1 along the second".
这个:
x[:][1]
表示取所有 x $的指数c $ c>沿着第一个轴(所有
x
),然后沿着结果的第一个轴取下索引1。您将 1
应用于错误的轴。
means "take all indices of x
along the first axis (so all of x
), then take index 1 along the first axis of the result". You're applying the 1
to the wrong axis.
x [1] [ 2]
和 x [1,2]
只是等价的,因为用整数索引数组会将所有剩余的轴移向形状的前面,所以 x [1]
的第一个轴是 x
的第二个轴。这根本没有概括;你应该几乎总是使用逗号而不是多个索引步骤。
x[1][2]
and x[1, 2]
are only equivalent because indexing an array with an integer shifts all remaining axes towards the front of the shape, so the first axis of x[1]
is the second axis of x
. This doesn't generalize at all; you should almost always use commas instead of multiple indexing steps.
这篇关于为什么用括号和逗号对索引的numpy数组的行为有所不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!