1

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.

1 Answer 1

1
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)
Sign up to request clarification or add additional context in comments.

1 Comment

Cheers! Way more elegant!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.