5
让我们以3D阵列为例。或者更容易形象化的立方体。从(n)D阵列中选择n-1个(n-1)D阵列
我想选择该立方体的所有面。我想将其推广到任意维度。
我还想然后添加/删除面的立方体(cuboid),并泛化为任意维。
我知道对于每个固定数量的维度你可以做array[:,:,0], array[-1,:,:]
我想知道如何推广到任意维度以及如何轻松遍历所有面。
让我们以3D阵列为例。或者更容易形象化的立方体。从(n)D阵列中选择n-1个(n-1)D阵列
我想选择该立方体的所有面。我想将其推广到任意维度。
我还想然后添加/删除面的立方体(cuboid),并泛化为任意维。
我知道对于每个固定数量的维度你可以做array[:,:,0], array[-1,:,:]
我想知道如何推广到任意维度以及如何轻松遍历所有面。
为了得到一张脸:
def get_face(M, dim, front_side):
if front_side:
side = 0
else:
side = -1
index = tuple(side if i == dim else slice(None) for i in range(M.ndim))
return M[index]
要添加一个面(未经测试):
def add_face(M, new_face, dim, front_side):
#assume sizes match up correctly
if front_side:
return np.concatenate((new_face, M), dim)
else:
return np.concatenate((M, new_face), dim)
要删除的脸:
def remove_face(M, dim, front_side):
if front_side:
dim_slice = slice(1, None)
else:
dim_slice = slice(None, -1)
index = tuple(dim_slice if i == dim else slice(None) for i in range(M.ndim))
return M[index]
遍历所有的面:
def iter_faces(M):
for dim in range(M.ndim):
for front_side in (True, False):
yield get_face(M, dim, front_side)
个
一些快速测试:
In [18]: M = np.arange(27).reshape((3,3,3))
In [19]: for face in iter_faces(M): print face
[[0 1 2]
[3 4 5]
[6 7 8]]
[[18 19 20]
[21 22 23]
[24 25 26]]
[[ 0 1 2]
[ 9 10 11]
[18 19 20]]
[[ 6 7 8]
[15 16 17]
[24 25 26]]
[[ 0 3 6]
[ 9 12 15]
[18 21 24]]
[[ 2 5 8]
[11 14 17]
[20 23 26]]
谢谢,我得到它的工作。 – csiz
除了巴斯的回答,在'访问numpy'一个常见的成语,以任意轴(例如'somefunc(somearray,axis = n)')是使用'swapaxes'来切换指定的轴与数组中的第一个轴,然后在“交换”结果的第一个轴上进行操作。 'swapaxes'显示视图,因此不会使用额外的内存。 –