简体   繁体   English

具有起始和结束索引列表的任意维的切片数组

[英]Slice array of arbitrary dimension with lists of start and end indices

I need to copy a part of a 3D array. 我需要复制3D阵列的一部分。 I have the indexes of start and end of the copy. 我有副本的开始和结束索引。

For example 2D array: 例如2D数组:

[[2 2 3 4 5]
 [2 3 3 4 5]
 [2 3 4 4 5]
 [2 3 4 5 5]
 [2 3 4 5 6]]

starting index, end index are: 起始索引,终止索引是:

mini = [2, 1]
maxi = [4, 3]

So the result should be: 因此结果应为:

  [[3 4 4]
   [3 4 5]]

I can write: 我可以写:

result = matrix[mini[0]:maxi[0], mini[1]:maxi[1]]

Is there a way to do it generally ? 一般有办法吗? for 3Dim or NDim arrays ? 3Dim或NDim阵列?

The trick here is realizing what the indexing syntax is under the hood. 这里的窍门是实现索引语法的本质。 This: 这个:

result = matrix[mini[0]:maxi[0], mini[1]:maxi[1]]

Is shorthand in python (not just numpy) for: 是python(不仅是numpy)的简写形式,用于:

indices = slice(mini[0], maxi[0]), slice(mini[1], maxi[1])
result = matrix[indices]

So we just need to generate indices dynamically: 因此,我们只需要动态生成indices

lower = [2, 1, ...]
upper = [4, 3, ...]

indices = tuple(np.s_[l:u] for l, u in zip(lower, upper))
result = matrix_nd[indices]

np.s_[a:b] is a shorthand for slice(a, b) . np.s_[a:b]slice(a, b)的简写。 Here we build a tuple containing as many slices as you have values in lower and upper 在这里,我们建立一个元组包含多达片,你在有价值观lowerupper

What you are looking for is the slice object, see that example: 您正在寻找的是slice对象,请参见该示例:

matrix = np.random.rand(4,5)
mini = [2, 1]
maxi = [4, 3]
slices=[slice(b,e) for b, e in zip(mini,maxi)]
print(slices)
print(matrix[slices])
print(matrix[mini[0]:maxi[0], mini[1]:maxi[1]])

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

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