0

条件如下:

1)我们有一个 ND 数组列表,这个列表的长度未知M

2) 每个数组的维度相等,但未知

3)每个数组应沿第 0 维拆分,结果元素应沿长度的第 1 维分组M,然后沿相同长度的第 0 维堆叠

4)结果排名应该是N+1,第一维的长度应该是M

以上与 相同zip,但在 ND 数组的世界中。

目前我执行以下方式:

xs = [list of numpy arrays]
grs = []
for i in range(len(xs[0])):
   gr = [x[i] for x in xs] 
   gr = np.stack(gr)
   grs.append(gr)
grs = np.stack(grs)

我可以用批量操作写得更短吗?

更新

这就是我想要的

将 numpy 导入为 np

sz = 2
sh = (30, 10, 10, 3)

xs = []
for i in range(sz):
    xs.append(np.zeros(sh, dtype=np.int))

value = 0

for i in range(sz):
    for index, _ in np.ndenumerate(xs[i]):
        xs[i][index] = value
        value += 1

grs = []
for i in range(len(xs[0])):
   gr = [x[i] for x in xs]
   gr = np.stack(gr)
   grs.append(gr)
grs = np.stack(grs)

print(np.shape(grs))

此代码显然可以正常工作,生成 shape 数组(30, 2, 10, 10, 3)。是否可以避免循环?

4

2 回答 2

1

Seems you need to transpose the array with respect to its 1st and 2nd dimension; You can use swapaxes for this:

np.asarray(xs).swapaxes(1,0)

Example:

xs = [np.array([[1,2],[3,4]]), np.array([[5,6],[7,8]])]
grs = []
for i in range(len(xs[0])):
    gr = [x[i] for x in xs] 
    gr = np.stack(gr)
    grs.append(gr)
grs = np.stack(grs)

grs
#array([[[1, 2],
#        [5, 6]],

#       [[3, 4],
#        [7, 8]]])

np.asarray(xs).swapaxes(1,0)
#array([[[1, 2],
#        [5, 6]],

#       [[3, 4],
#        [7, 8]]])
于 2017-07-28T18:22:08.793 回答
0

np.stack接受一个轴参数;看着 的形状grs,我猜这np.stack(xs, 1)也是一样的。

In [490]: x
Out[490]: 
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
In [491]: x.shape
Out[491]: (2, 3, 4)
In [494]: xs = [x, x+10, x+100]
In [495]: grs = []
     ...: for i in range(len(xs[0])):
     ...:    gr = [x[i] for x in xs] 
     ...:    gr = np.stack(gr)
     ...:    grs.append(gr)
     ...: grs = np.stack(grs)
     ...: 
In [496]: grs
Out[496]: 
array([[[[  0,   1,   2,   3],
         [  4,   5,   6,   7],
         [  8,   9,  10,  11]],

        [[ 10,  11,  12,  13],
         [ 14,  15,  16,  17],
         [ 18,  19,  20,  21]],

        [[100, 101, 102, 103],
         [104, 105, 106, 107],
         ...
         [116, 117, 118, 119],
         [120, 121, 122, 123]]]])
In [497]: grs.shape
Out[497]: (2, 3, 3, 4)

测试np.stack

In [499]: np.allclose(np.stack(xs, 1),grs)
Out[499]: True
于 2017-07-28T23:25:24.883 回答