Numpy split cube into cubes

前端 未结 3 1736
南方客
南方客 2021-02-09 04:01

There is a function np.split() which can split an array along 1 axis. I was wondering if there was a multi axis version where you can split along axes (0,1,2) for e

3条回答
  •  时光说笑
    2021-02-09 04:19

    I don't think there is a multi axis version where you can split along some given axes. But you can split it up one dimension at a time. For example like this:

    def split2(arys, sections, axis=[0, 1]):
        if not isinstance(arys, list):
             arys = [arys]
        for ax in axis:
            arys = [np.split(ary, sections, axis=ax) for ary in arys]
            arys = [ary for aa in arys for ary in aa]  # Flatten
        return arys
    

    It can be used like this:

    In [1]: a = np.array(range(100)).reshape(10, 10)
    In [2]: split2(a, 2, axis=[0, 1])
    Out[2]:
    [array([[ 0,  1,  2,  3,  4],
           [10, 11, 12, 13, 14],
           [20, 21, 22, 23, 24],
           [30, 31, 32, 33, 34],
           [40, 41, 42, 43, 44]]),
     array([[ 5,  6,  7,  8,  9],
           [15, 16, 17, 18, 19],
           [25, 26, 27, 28, 29],
           [35, 36, 37, 38, 39],
           [45, 46, 47, 48, 49]]),
     array([[50, 51, 52, 53, 54],
           [60, 61, 62, 63, 64],
           [70, 71, 72, 73, 74],
           [80, 81, 82, 83, 84],
           [90, 91, 92, 93, 94]]),
     array([[55, 56, 57, 58, 59],
           [65, 66, 67, 68, 69],
           [75, 76, 77, 78, 79],
           [85, 86, 87, 88, 89],
           [95, 96, 97, 98, 99]])]
    

提交回复
热议问题