[英]numpy array slicing with arbitrary dimension
Say I create an array of arbitrary dimension (n). 假设我创建了一个任意维度的数组(n)。
#assign the dimension
>>> n=22
#create the numpy array
>>> TheArray=zeros([2]*n)
>>> shape(TheArray)
(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
Have some code (skipped in this example) to populate the values of the array. 有一些代码(在本例中跳过)来填充数组的值。
Now, try to access some values of the array 现在,尝试访问数组的某些值
>>> TheArray[0:2,0:2,0:2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
array([[[ 0., 0.],
[ 0., 0.]],
[[ 0., 0.],
[ 0., 0.]]])
How to make the 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
part of the syntax generalized to n? 如何将
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
部分语法推广到n?
One way would be to use numpy.s_ : 一种方法是使用numpy.s_ :
In [55]: m = arange(2**6).reshape([2]*6)
In [56]: m.shape
Out[56]: (2, 2, 2, 2, 2, 2)
In [57]: m[:2,:2,:2,0,0,0]
Out[57]:
array([[[ 0, 8],
[16, 24]],
[[32, 40],
[48, 56]]])
In [58]: m[s_[:2, :2, :2] + (0,)*(n-3)]
Out[58]:
array([[[ 0, 8],
[16, 24]],
[[32, 40],
[48, 56]]])
And I guess you could get rid of the hardcoded -3.. 而且我猜你可以摆脱硬编码-3 ..
In [69]: m[(s_[:2, :2, :2] + (0,)*m.ndim)[:m.ndim]]
Out[69]:
array([[[ 0, 8],
[16, 24]],
[[32, 40],
[48, 56]]])
but to be honest, I'd probably just wrap this up in a function if I needed it. 但说实话,如果需要的话,我可能只是把它包装成一个函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.