Home > Blockchain >  transpose sub-blocks of numpy array
transpose sub-blocks of numpy array

Time:11-29

I have a Numpy array which consists of several square sub-blocks. For example:

A = [A_1 | A_2 | ... A_n],

each of them has the same size. I would like to transpose it in the following way:

B = [A_1^T | A_2^T| ... A_n^T].

Is there a way to do it instead of slicing the original array and then transposing each sub-block?

CodePudding user response:

Assuming that A_i has shape (M, M), I can see two scenarios:

  1. Your entire array A is already in shape (N, M, M). In this case, you can transpose the submatrices A_i using np.ndarray.swapaxes or np.ndarray.transpose. Example:
A = np.arange(36).reshape(4, 3, 3)

# 4 submatrices A_0 ... A_3 each with shape (3, 3)
# 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],
#         [24, 25, 26]],
# 
#        [[27, 28, 29],
#         [30, 31, 32],
#         [33, 34, 35]]])

B = A.swapaxes(1, 2)

# The submatrices are transposed:
# array([[[ 0,  3,  6],
#         [ 1,  4,  7],
#         [ 2,  5,  8]],
# 
#        [[ 9, 12, 15],
#         [10, 13, 16],
#         [11, 14, 17]],
# 
#        [[18, 21, 24],
#         [19, 22, 25],
#         [20, 23, 26]],
# 
#        [[27, 30, 33],
#         [28, 31, 34],
#         [29, 32, 35]]])
  1. Your entire array A has only two dimensions, i.e. shape (M, N * M). In this case, you can bring your array to three dimensions first, then swap the axes, and then shape your array back to 2 dimensions. Example:
A = np.arange(36).reshape(3, 12)

# 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],
#        [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]])
# A_i:    ^^^^^^^^^^  ^^^^^^^^^^  ^^^^^^^^^^  ^^^^^^^^^^

B = A.reshape(3, 4, 3).swapaxes(0, 2).reshape(3, 12)

# array([[ 0, 12, 24,  3, 15, 27,  6, 18, 30,  9, 21, 33],
#        [ 1, 13, 25,  4, 16, 28,  7, 19, 31, 10, 22, 34],
#        [ 2, 14, 26,  5, 17, 29,  8, 20, 32, 11, 23, 35]])
# A_i^T:  ^^^^^^^^^^  ^^^^^^^^^^  ^^^^^^^^^^  ^^^^^^^^^^
  • Related