问题描述
我倾向于用括号索引 numpy 数组(矩阵),但我注意到当我想对数组(矩阵)进行切片时,我必须使用逗号表示法.为什么是这样?例如,
>>>x = numpy.array([[1, 2], [3, 4], [5, 6]])>>>X数组([[1, 2],[3, 4],[5, 6]])>>>x[1][1]4 # 预期行为>>>x[1,1]4 # 预期行为>>>x[:][1]数组([3, 4]) # 嗯?>>>x[:,1]array([2, 4, 6]) # 预期行为这个:
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.
这篇关于为什么用括号和逗号索引 numpy 数组的行为不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!