How to reshape matrices using index instead of shape inputs?

Question:

Given an array of shape (8, 3, 4, 4), reshape them into an arbitrary new shape (8, 4, 4, 3) by inputting the new indices compared to the old positions (0, 2, 3, 1).

Asked By: mariogarcc

||

Answers:

Numpy’s transpose "reverses or permutes":

>>> mat = np.ones((8, 3, 4, 4))
>>> new_indices = (0, 2, 3, 1)
>>> mat.transpose(new_indices).shape
(8, 4, 4, 3)
Answered By: mariogarcc

Maybe this is what you are looking for:

arr = np.array([[[1, 2], [3, 4], [5, 6]]])
s = arr.shape
new_indexes = (1, 0, 2) # permutation
new_arr = arr.reshape(*[s[index] for index in new_indexes])

print(arr.shape) # (1, 3, 2)
print(new_arr.shape) # (3, 1, 2)

Answered By: Phoenixo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.