zeniapy
zeniapy

Reputation: 175

Expand Multi-Dimensional Numpy Array

I have a [2x2x2] numpy array a and want to expand it to [4x4x4] like b. The premise is to expand the values as well. It´s supposed to look something like this:

 a = array([[[1, 2],
             [-2, -1]],
            [[3, -4],
             [4, -3]]])

 b = array([[[1, 1, 2, 2],
             [1, 1, 2, 2],  
             [-2, -2, -1, -1],
             [-2, -2, -1, -1]],
            [[1, 1, 2, 2],
             [1, 1, 2, 2],  
             [-2, -2, -1, -1],
             [-2, -2, -1, -1]],
            [[3, 3, -4, -4],
             [3, 3, -4, -4],  
             [4, 4, -3, -3],
             [4, 4, -3, -3]],
            [[3, 3, -4, -4],
             [3, 3, -4, -4],  
             [4, 4, -3, -3],
             [4, 4, -3, -3]]])

Loosely said each value of a expands into a [2x2x2] of the same value.

My current attempt is just hard coded.

b = np.zeros(shape=(4, 4, 4), dtype='int')
b[0:2, 0:2, 0:2] = a[0, 0, 0]
b[0:2, 0:2, 2:] = a[0, 0, 1]
b[0:2, 2:, 2:] = a[0, 1, 1]
b[0:2, 2:, 0:2] = a[0, 1, 0]
b[2:, 0:2, 0:2] = a[1, 0, 0]
b[2:, 0:2, 2:] = a[1, 0, 1]
b[2:, 2:, 2:] = a[1, 1, 1]
b[2:, 2:, 0:2] = a[1, 1, 0]

This should definitely be easier. Thanks.

Upvotes: 1

Views: 37

Answers (1)

Stef
Stef

Reputation: 30579

b = np.insert(a, slice(0,2), a, 2)
b = np.insert(b, slice(0,2), b, 1)
b = np.insert(b, slice(0,2), b, 0)

Result:

array([[[ 1,  1,  2,  2],
        [ 1,  1,  2,  2],
        [-2, -2, -1, -1],
        [-2, -2, -1, -1]],

       [[ 1,  1,  2,  2],
        [ 1,  1,  2,  2],
        [-2, -2, -1, -1],
        [-2, -2, -1, -1]],

       [[ 3,  3, -4, -4],
        [ 3,  3, -4, -4],
        [ 4,  4, -3, -3],
        [ 4,  4, -3, -3]],

       [[ 3,  3, -4, -4],
        [ 3,  3, -4, -4],
        [ 4,  4, -3, -3],
        [ 4,  4, -3, -3]]])

Or, if it's OK to overwrite a, simply:

for axis in range(3):
    a = np.insert(a, slice(0,2), a, axis)

Upvotes: 1

Related Questions