简体   繁体   English

Numpy:想要在 ndarray 中选择不同的维度范围

[英]Numpy: Want to select Different range of dimension in ndarray

I believe it is a simple question, but I am stuck with it.我相信这是一个简单的问题,但我坚持下去。 I'm picking specific dimensions from a tensor like我从像这样的张量中选择特定的尺寸

input = x[i, :, 38:44]

Everything was fine until this point, but now I want to extract a different range of dimensions, such as:到目前为止一切都很好,但现在我想提取不同的维度范围,例如:

38:44 then 46 to 48 then 50 to 54. How can we do this? 38:44 then 46 to 48 then 50 to 54.我们怎样才能做到这一点?

You send a list with the desired indices.您发送一个包含所需索引的列表。 For example, consider the following array:例如,考虑以下数组:

import numpy as np
arr = np.array([[1,2], [2,3], [4,5], [6,7], [8,9]])

We can retrieve indices with the following way:我们可以通过以下方式检索索引:

arr[[0,1,3], :]

Output:输出:

array([[1, 2],
       [2, 3],
       [6, 7]])

Here I created a list of desired indices [0,1,3] and send as retrieve the relevant dimensions.在这里,我创建了所需索引[0,1,3]的列表,并将相关维度作为检索对象发送。

So as for your question, you get declare whenever indices you want:因此,对于您的问题,您可以随时声明所需的索引:

desired_indices = list(range(38,44)) + list(range(46,48)) + list(range(50,54))
my_input = x[i, :, desired_indices]

(I also change the "input" from the variable name as it will create a problem) (我还更改了变量名中的“输入”,因为它会产生问题)

The question of how to take multiple slices has come up often on SO.如何取多个切片的问题经常出现在 SO 上。

If the slices are regular enough you may be able reshape the array, and take just one slice.如果切片足够规则,您可以重塑阵列,并只取一片。

But more generally you have 2 options:但更一般地说,您有两种选择:

  • take the slices separately, and join them ( np.concatenate )分别取切片,然后加入它们( np.concatenate

  • construct an advanced indexing array, and apply that.构造一个高级索引数组,并应用它。 If the slices all have the same length you might make the array with linspace or a bit of broadcasted math.如果切片都具有相同的长度,您可以使用linspace或一些广播数学来制作数组。 But if they differ, you have to concatenate a bunch of arange .但如果它们不同,则必须连接一堆arange

With x[i, :, arr] where arr is an array like np.array([38,39,50,60]) , there is a complicating factor that it mixes basic and advanced indexing.对于x[i, :, arr]其中arr是一个类似np.array([38,39,50,60])的数组,有一个复杂的因素是它混合了基本索引和高级索引。 It is well known, at least among experienced numpy users, that this gives an unexpected shape, with the slice dimension(s) moved to the end.众所周知,至少在有经验的 numpy 用户中,这会产生意想不到的形状,切片维度移动到末尾。

x[i][:,arr] is one way around this. x[i][:,arr]是解决这个问题的一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM