从numpy中的(n)D数组中选择(n-1)D数组

csi*_*siz 5 python numpy

让我们以3D阵列为例.或者是一个易于可视化的立方体.

我想选择那个立方体的所有面孔.我想将其概括为任意维度.

我还想在多维数据集中添加/删除面(长方体),并将其推广到任意维度.

我知道,对于每个固定数量的维度,我都可以array[:,:,0], array[-1,:,:]知道如何推广到任意维度以及如何轻松迭代所有面.

Bas*_*els 4

获得一张脸:

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]
Run Code Online (Sandbox Code Playgroud)

添加脸部(未经测试):

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)
Run Code Online (Sandbox Code Playgroud)

删除脸部:

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]
Run Code Online (Sandbox Code Playgroud)

迭代所有面:

def iter_faces(M):
    for dim in range(M.ndim):
        for front_side in (True, False):
            yield get_face(M, dim, front_side)
Run Code Online (Sandbox Code Playgroud)

一些快速测试:

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]]
Run Code Online (Sandbox Code Playgroud)