为什么用括号和逗号索引 numpy 数组的行为不同? [英] Why does indexing numpy arrays with brackets and commas differ in behavior?

查看:23
本文介绍了为什么用括号和逗号索引 numpy 数组的行为不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我倾向于用括号索引 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 数组的行为不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆