First let's put that out of the way: I'm already aware of the solution discussed here: Create NumPy array from another array by specifying rows and columns
Let's say I have an array
test = np.arange(12).reshape((3,4))
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
and I want to rearrange its rows and columns into test2
array([[ 1, 0, 3, 2],
[ 9, 8, 11, 10],
[ 5, 4, 7, 6]])
The solution I'm using right now is the same as the one already answered in the link above:
test2 = test[[0,2,1]][:,[1,0,3,2]]
However this solution creates an unnecessary intermediate copy of the data: it first creates a copy with shuffled rows only test[[0,2,1]]
, then creates a second copy with shuffled columns as well. For such a small array, no one cares but if the array is gigantic this solution feels sub-optimal. Does numpy allow rows and columns shuffling simultaneously? Something looking like test[[0,2,1],[1,0,3,2]]
, except numpy doesn't interpret this operation that way...