且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么用括号和逗号索引 numpy 数组的行为不同?

更新时间:2023-02-18 16:46:22

这个:

x[:, 1]

表示沿第一个轴获取 x 的所有索引,但沿第二个轴仅获取索引 1".

这个:

x[:][1]

表示沿第一轴取x的所有索引(所以所有x),然后沿第一轴取索引1结果".您将 1 应用于错误的轴.

x[1][2]x[1, 2] 只是等价的,因为用整数索引数组会将所有剩余的轴移向数组的前面形状,所以 x[1] 的第一个轴是 x 的第二个轴.这根本不能概括;您应该几乎总是使用逗号而不是多个索引步骤.

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

This:

x[:, 1]

means "take all indices of x along the first axis, but only index 1 along the second".

This:

x[:][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] 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.