[英]Get range/slice from numpy array the size of another array
I have two numpy arrays, one bigger than another, but both with the same number of dimensions. 我有两个numpy数组,一个大于另一个,但两个数组的维数相同。
I want to get a slice from the bigger array that matches the size of the smaller array. 我想从较大的数组中获取一个切片,该切片与较小的数组的大小匹配。 (Starting from 0,0,0....
) (从0,0,0....
开始)
So, imagine the big array has shape (10,5,7). 因此,想象一下大数组的形状为(10,5,7)。
And the small array has shape (10,4,6). 小阵列的形状为(10,4,6)。
I want to get from the bigger array this slice: 我想从更大的数组中得到这个切片:
biggerArray[:10,:4,:6]
The length of the shape tuple may vary, and I want to do it for any number of dimensions (Both will always have the same number of dimensions). 形状元组的长度可能会有所不同,我想对任何数量的尺寸都使用它(两个尺寸总是相同)。
How to do that? 怎么做? Is there a way to use tuples as ranges in slices? 有没有一种方法可以将元组用作切片中的范围?
Construct the tuple of slice
objects manually. 手动构造slice
对象的元组。 biggerArray[:10, :4, :6]
is syntactic sugar for biggerArray[(slice(10), slice(4), slice(6))]
, so: biggerArray[:10, :4, :6]
是biggerArray[(slice(10), slice(4), slice(6))]
语法糖,所以:
biggerArray[tuple(map(slice, smallerArray.shape))]
or 要么
biggerArray[tuple(slice(0, n) for n in smallerArray.shape)]
You may want to assert result.shape == smallerArray.shape
afterwards, just in case the input shapes weren't what you thought they were. 之后,您可能要assert result.shape == smallerArray.shape
,以防输入形状不符合您的想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.