numpy数组切片意外的结果 [英] numpy array slicing unxpected results
问题描述
我不了解以下行为.通常可以通过索引访问numpy数组,因此[:,1]应该等效于[:] [1],或者我认为.有人可以解释为什么不是这种情况吗?
I don't understand the behavior below. numpy arrays can generally be accessed through indexing, so [:,1] should be equivalent to [:][1], or so I thought. Could someone explain why this is not the case?
>>> a = np.array([[1, 2, 3], [4, 5, 6]])
>>> a[:,1]
array([2, 5])
>>> a[:][1]
array([4, 5, 6])
谢谢!
推荐答案
这两种索引形式不同.您应该使用[i, j]
而不是[i][j]
.即使两者都可行,第一个也会更快(请参见此问题 ).
Those two forms of indexing are not the same. You should use [i, j]
and not [i][j]
. Even where both work, the first will be faster (see this question).
使用两个索引[i][j]
是两个操作.它执行第一个索引,然后对第一个操作的结果执行第二个索引. [:]
仅返回整个数组,因此您的第一个等效于array[1]
.由于仅传递了一个索引,因此它假定引用的是第一维(行),因此这意味着获取行1".使用一个复合索引[i, j]
是一次使用两个索引条件的单一操作,因此array[:, 1]
返回所有行,列1".
Using two indices [i][j]
is two operations. It does the first index and then does the second on the result of the first operation. [:]
just returns the entire array, so your first one is equivalent to array[1]
. Since only one index is passed, it assumed to refer to the first dimension (rows), so this means "get row 1". Using one compound index [i, j]
is a single operation that uses both indexing conditions at once, so array[:, 1]
returns "all rows, column 1".
这篇关于numpy数组切片意外的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!