简体   繁体   English

裁剪给定两个角的任意维度的NumPy数组

[英]Cropping a NumPy array of an arbitrary dimension given two corners

There are several posts for slicing 2D and 3D NumPy arrays, but in my program dimension of the array is not known. 有几个关于切片2D和3D NumPy数组的文章,但是在我的程序中,数组的尺寸未知。 Consider a NumPy ndarray A of arbitrary dimension n (positive integer), and shape D=[d1,...,dn] ( di s nonnegative integers), For example: 考虑一个任意维度为n (正整数)且形状为D=[d1,...,dn]di s为非负整数)的NumPy ndarray A ,例如:

import numpy as np

D=np.array([2,3,4,5])

A=np.random.rand(*D)

Now I need to extract a block of A starting from D1=[d11,...,d1n] to D2=[d21,...,d2n] , where for all 0<i<=n : 0<=d1i<=d2i<=di . 现在我需要提取的一个块A从开始D1=[d11,...,d1n]D2=[d21,...,d2n]其中对于所有0<i<=n : 0<=d1i<=d2i<=di Something like: 就像是:

A[D1:D2]

If I new n then I could simple use A[d11:d21,...,d1i:d2i,...,d1n:d2n] , but that's not the case for me. 如果我新创建了n那么我可以简单地使用A[d11:d21,...,d1i:d2i,...,d1n:d2n] ,但对我而言并非如此。 I would appreciate if you could help me know what is the most efficient way of cropping A given D1 and D2 . 我将不胜感激,如果你能帮助我知道了什么是种植的最有效的方式A给定的D1D2

The portion of the numpy indexing page that @Joe referred to is likely this: @Joe所指的numpy索引页面的部分可能是这样的:

Note 注意
Remember that a slicing tuple can always be constructed as obj and used in the x[obj] notation. 请记住,切片元组始终可以构造为obj并以x[obj]表示法使用。 Slice objects can be used in the construction in place of the [start:stop:step] notation. 切片对象可以在构造中使用[start:stop:step]表示法代替。 For example, x[1:10:5,::-1] can also be implemented as: 例如, x[1:10:5,::-1]也可以实现为:

obj = (slice(1,10,5), slice(None,None,-1))
x[obj]

This can be useful for constructing generic code that works on arrays of arbitrary dimension. 这对于构造可用于任意维数组的通用代码很有用。

Using this concept you should be able to build your tuple of slices ahead of time then apply it to A . 使用此概念,您应该能够提前构建切片的元组,然后将其应用于A

obj = tuple(slice(D1[i], D2[i]) for i in range(D1.shape[0]))
A[obj]

Note* this is not actually using advanced indexing, as you are still providing a tuple of slice objects which is just the longhand / functional equivalent of using slices separated by colons and commas: A[d11:d21, ... Advanced indexing utilizes arrays of different datatypes rather than exclusively tuples of slice objects. 注意*这实际上并没有使用高级索引,因为您仍在提供切片对象的元组,这与使用以冒号和逗号分隔的切片的手/功能等效: A[d11:d21, ...高级索引使用数组不同的数据类型,而不是专门用于slice对象的元组。

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

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