numpy数组切片意外的结果

编程入门 行业动态 更新时间:2024-10-25 21:17:57
本文介绍了numpy数组切片意外的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我不了解以下行为.通常可以通过索引访问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数组切片意外的结果

本文发布于:2023-11-13 14:16:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584546.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   切片   意外   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!