Numpy数组的范围索引

huangapple go评论64阅读模式
英文:

Range indexing in Numpy Array

问题

我在使用numpy数组的范围索引时遇到了一些困难。

在MATLAB中,我会这样做:

array(:,4:end) 以获取所有行和从第4列开始的所有列。

在Python中,array[-1] 会获取最后一个元素,但是根据我的测试,array[:,3:-1] 不会获取最后一列(它会找到所有行和从第4列开始的所有列,但不包括最后一列,最后一列被跳过了)。

是否有人知道在范围索引时索引最后一个元素的简便方法,这样我就不必每次创建一个数组时都自己解决这个问题了?提前感谢。

我尝试验证 array[0:-1] 是否包含整个数组,但结果并不是这样的。

英文:

I’m having difficulty with finding a nice way of accessing the last elements with range-indexing of a numpy array.

In MATLAB, I would do this:

array(:,4:end) to grab all rows and columns 4 and up.

array[-1] in python will grab the last element, but array[:,3:-1] will from my testing not grab the last column (it would find all rows and columns 4 and up, except for the very last column, which is skipped).

Does anyone know of a shorthand way of indexing the last element when range-indexing so that I don’t have to figure it out myself every time I make an array? Thanks in advance.

I tried verifying if array[0:-1] carries the whole array, but it does not.

答案1

得分: 0

在Python中索引数组时,切片从起始位置(包括起始位置)开始,到结束位置(不包括结束位置)结束。因此,使用 arr[:, 3:-1] 将返回每一行和从第4列到倒数第二列的所有列。

如果您想一直切片到最后,将停止参数留空,即写成 arr[:, 3:]

英文:

When indexing an array in python, the slice is inclusive of the start and exclusive of the end. So, using arr[:, 3:-1] will return every row and columns 4 up to but not including the last column.

If you want to slice all the way to the end, leave the stop argument blank, i.e. write arr[:, 3:].

huangapple
  • 本文由 发表于 2023年7月3日 14:05:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76602190.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定